# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.async_support.base.exchange import Exchange from ccxt.abstract.woofipro import ImplicitAPI import asyncio from ccxt.base.types import Balances, Currencies, Currency, CurrencyInterface, FundingHistory, Int, LedgerEntry, Leverage, MarginMode, MarginModes, MarginModification, Market, Num, Order, OrderBook, OrderRequest, OrderSide, OrderType, Position, Status, Str, Strings, Ticker, Tickers, FundingRate, OpenInterest, FundingRates, OpenInterests, Trade, TradingFees, Transaction, FundingRateHistory from ccxt.base.errors import ExchangeError from ccxt.base.errors import AuthenticationError from ccxt.base.errors import ArgumentsRequired from ccxt.base.errors import BadRequest from ccxt.base.errors import BadSymbol from ccxt.base.errors import InsufficientFunds from ccxt.base.errors import InvalidOrder from ccxt.base.errors import NotSupported from ccxt.base.errors import NetworkError from ccxt.base.errors import RateLimitExceeded from ccxt.base.decimal_to_precision import TICK_SIZE from ccxt.base.precise import Precise class woofipro(Exchange, ImplicitAPI): def describe(self) -> dict: return self.deep_extend(super(woofipro, self).describe(), { 'id': 'woofipro', 'name': 'WOOFI PRO', 'countries': ['KY'], # Cayman Islands 'rateLimit': 100, 'version': 'v1', 'certified': True, 'pro': True, 'dex': True, 'has': { 'CORS': None, 'spot': False, 'margin': False, 'swap': True, 'future': False, 'option': False, 'addMargin': True, 'borrowCrossMargin': False, 'borrowIsolatedMargin': False, 'borrowMargin': False, 'cancelAllOrders': True, 'cancelOrder': True, 'cancelOrders': True, 'cancelWithdraw': False, 'closeAllPositions': False, 'closePosition': False, 'createConvertTrade': False, 'createDepositAddress': False, 'createMarketBuyOrderWithCost': False, 'createMarketOrder': False, 'createMarketOrderWithCost': False, 'createMarketSellOrderWithCost': False, 'createOrder': True, 'createOrders': True, 'createOrderWithTakeProfitAndStopLoss': True, 'createReduceOnlyOrder': True, 'createStopLimitOrder': False, 'createStopLossOrder': True, 'createStopMarketOrder': False, 'createStopOrder': False, 'createTakeProfitOrder': True, 'createTrailingAmountOrder': False, 'createTrailingPercentOrder': False, 'createTriggerOrder': True, 'editOrder': True, 'fetchAccounts': False, 'fetchAllGreeks': False, 'fetchBalance': True, 'fetchBorrowInterest': False, 'fetchBorrowRate': False, 'fetchBorrowRateHistories': False, 'fetchBorrowRateHistory': False, 'fetchBorrowRates': False, 'fetchBorrowRatesPerSymbol': False, 'fetchCanceledOrders': False, 'fetchClosedOrder': False, 'fetchClosedOrders': True, 'fetchConvertCurrencies': False, 'fetchConvertQuote': False, 'fetchCrossBorrowRate': False, 'fetchCrossBorrowRates': False, 'fetchCurrencies': True, 'fetchDepositAddress': False, 'fetchDeposits': True, 'fetchDepositsWithdrawals': True, 'fetchFundingHistory': True, 'fetchFundingInterval': True, 'fetchFundingIntervals': False, 'fetchFundingRate': True, 'fetchFundingRateHistory': True, 'fetchFundingRates': True, 'fetchGreeks': False, 'fetchIndexOHLCV': False, 'fetchIsolatedBorrowRate': False, 'fetchIsolatedBorrowRates': False, 'fetchLedger': True, 'fetchLeverage': True, 'fetchMarginAdjustmentHistory': False, 'fetchMarginMode': True, 'fetchMarginModes': True, 'fetchMarkets': True, 'fetchMarkOHLCV': False, 'fetchMyTrades': True, 'fetchOHLCV': True, 'fetchOpenInterest': True, 'fetchOpenInterestHistory': False, 'fetchOpenInterests': True, 'fetchOpenOrder': False, 'fetchOpenOrders': True, 'fetchOption': False, 'fetchOptionChain': False, 'fetchOrder': True, 'fetchOrderBook': True, 'fetchOrders': True, 'fetchOrderTrades': True, 'fetchPosition': True, 'fetchPositionMode': False, 'fetchPositions': True, 'fetchPremiumIndexOHLCV': False, 'fetchStatus': True, 'fetchTicker': True, 'fetchTickers': True, 'fetchTime': True, 'fetchTrades': True, 'fetchTradingFee': False, 'fetchTradingFees': True, 'fetchTransactions': 'emulated', 'fetchTransfers': False, 'fetchVolatilityHistory': False, 'fetchWithdrawals': True, 'reduceMargin': True, 'repayCrossMargin': False, 'repayIsolatedMargin': False, 'setLeverage': True, 'setMargin': False, 'setMarginMode': True, 'setPositionMode': False, 'transfer': False, 'withdraw': True, # exchange have that endpoint disabled atm, but was once implemented in ccxt per old docs: https://kronosresearch.github.io/wootrade-documents/#token-withdraw }, 'timeframes': { '1m': '1m', '5m': '5m', '15m': '15m', '30m': '30m', '1h': '1h', '4h': '4h', '12h': '12h', '1d': '1d', '1w': '1w', '1M': '1mon', '1y': '1y', }, 'urls': { 'logo': 'https://github.com/user-attachments/assets/9ba21b8a-a9c7-4770-b7f1-ce3bcbde68c1', 'api': { 'public': 'https://api-evm.orderly.org', 'private': 'https://api-evm.orderly.org', }, 'test': { 'public': 'https://testnet-api-evm.orderly.org', 'private': 'https://testnet-api-evm.orderly.org', }, 'www': 'https://dex.woo.org', 'doc': [ 'https://orderly.network/docs/build-on-omnichain/building-on-omnichain', ], 'fees': [ 'https://dex.woo.org/en/orderly', ], 'referral': { 'url': 'https://dex.woo.org/en/trade?ref=CCXT', 'discount': 0.05, }, }, 'api': { 'v1': { 'public': { 'get': { 'public/volume/stats': {'cost': 1}, 'public/broker/name': {'cost': 1}, 'public/chain_info/{broker_id}': {'cost': 1}, 'public/system_info': {'cost': 1}, 'public/vault_balance': {'cost': 1}, 'public/insurancefund': {'cost': 1}, 'public/chain_info': {'cost': 1}, 'faucet/usdc': {'cost': 1}, 'public/account': {'cost': 1}, 'get_account': {'cost': 1}, 'registration_nonce': {'cost': 1}, 'get_orderly_key': {'cost': 1}, 'public/liquidation': {'cost': 1}, 'public/liquidated_positions': {'cost': 1}, 'public/config': {'cost': 1}, 'public/campaign/ranking': {'cost': 10}, 'public/campaign/stats': {'cost': 10}, 'public/campaign/user': {'cost': 10}, 'public/campaign/stats/details': {'cost': 10}, 'public/campaigns': {'cost': 10}, 'public/points/leaderboard': {'cost': 1}, 'client/points': {'cost': 1}, 'public/points/epoch': {'cost': 1}, 'public/points/epoch_dates': {'cost': 1}, 'public/points/rankings': {'cost': 1}, 'public/points/stages': {'cost': 1}, 'public/referral/check_ref_code': {'cost': 1}, 'public/referral/verify_ref_code': {'cost': 1}, 'referral/admin_info': {'cost': 1}, 'referral/info': {'cost': 1}, 'referral/referee_info': {'cost': 1}, 'referral/referee_rebate_summary': {'cost': 1}, 'referral/referee_history': {'cost': 1}, 'referral/referral_history': {'cost': 1}, 'referral/rebate_summary': {'cost': 1}, 'client/distribution_history': {'cost': 1}, 'tv/config': {'cost': 1}, 'tv/history': {'cost': 1}, 'tv/symbol_info': {'cost': 1}, 'tv/kline_history': {'cost': 1}, 'public/funding_rate_history': {'cost': 1}, 'public/funding_rate/{symbol}': {'cost': 0.33}, 'public/funding_rates': {'cost': 1}, 'public/info': {'cost': 1}, 'public/info/{symbol}': {'cost': 1}, 'public/market_trades': {'cost': 1}, 'public/token': {'cost': 1}, 'public/futures': {'cost': 1}, 'public/futures/{symbol}': {'cost': 1}, 'staking/valor2/batch_info': {'cost': 1}, 'staking/valor2/pool_info': {'cost': 1}, 'staking/valor2/revenue_buyback': {'cost': 1}, }, 'post': { 'register_account': {'cost': 1}, }, }, 'private': { 'get': { 'client/key_info': {'cost': 6}, 'client/orderly_key_ip_restriction': {'cost': 6}, 'order/{oid}': {'cost': 1}, 'client/order/{client_order_id}': {'cost': 1}, 'algo/order/{oid}': {'cost': 1}, 'algo/client/order/{client_order_id}': {'cost': 1}, 'orders': {'cost': 1}, 'algo/orders': {'cost': 1}, 'trade/{tid}': {'cost': 1}, 'trades': {'cost': 1}, 'order/{oid}/trades': {'cost': 1}, 'client/liquidator_liquidations': {'cost': 1}, 'liquidations': {'cost': 1}, 'asset/history': {'cost': 60}, 'client/holding': {'cost': 1}, 'withdraw_nonce': {'cost': 1}, 'settle_nonce': {'cost': 1}, 'transfer_nonce': {'cost': 1}, 'pnl_settlement/history': {'cost': 1}, 'volume/user/daily': {'cost': 60}, 'volume/user/stats': {'cost': 60}, 'client/statistics': {'cost': 60}, 'client/info': {'cost': 60}, 'client/statistics/daily': {'cost': 60}, 'positions': {'cost': 3.33}, 'position/{symbol}': {'cost': 3.33}, 'funding_fee/history': {'cost': 30}, 'notification/inbox/notifications': {'cost': 60}, 'notification/inbox/unread': {'cost': 60}, 'volume/broker/daily': {'cost': 60}, 'broker/fee_rate/default': {'cost': 10}, 'broker/user_info': {'cost': 10}, 'broker/daily_fee_revenue': {'cost': 10}, 'orderbook/{symbol}': {'cost': 1}, 'kline': {'cost': 1}, 'client/margin_modes': {'cost': 1}, 'client/leverages': {'cost': 1}, 'client/points/user_statistics': {'cost': 1}, 'staking/valor2/redeem': {'cost': 1}, 'referral/multi_level/admin': {'cost': 1}, 'referral/multi_level/admin/info': {'cost': 1}, 'referral/multi_level/admin/referee_list': {'cost': 1}, 'referral/multi_level/admin/summary': {'cost': 1}, 'referral/multi_level/max_rebate_rate': {'cost': 1}, 'referral/multi_level/rebate_info': {'cost': 1}, 'referral/multi_level/referee_list': {'cost': 1}, 'referral/multi_level/statistics': {'cost': 1}, 'referral/multi_level/volume_prerequisite': {'cost': 1}, }, 'post': { 'orderly_key': {'cost': 1}, 'client/set_orderly_key_ip_restriction': {'cost': 6}, 'client/reset_orderly_key_ip_restriction': {'cost': 6}, 'order': {'cost': 1}, 'batch-order': {'cost': 10}, 'algo/order': {'cost': 1}, 'liquidation': {'cost': 1}, 'claim_insurance_fund': {'cost': 1}, 'withdraw_request': {'cost': 1}, 'settle_pnl': {'cost': 1}, 'notification/inbox/mark_read': {'cost': 60}, 'notification/inbox/mark_read_all': {'cost': 60}, 'client/leverage': {'cost': 120}, 'client/leverages': {'cost': 120}, 'client/margin_mode': {'cost': 1}, 'position_margin': {'cost': 1}, 'client/maintenance_config': {'cost': 60}, 'delegate_signer': {'cost': 10}, 'delegate_orderly_key': {'cost': 10}, 'delegate_settle_pnl': {'cost': 10}, 'delegate_withdraw_request': {'cost': 10}, 'broker/fee_rate/set': {'cost': 10}, 'broker/fee_rate/set_default': {'cost': 10}, 'broker/fee_rate/default': {'cost': 10}, 'referral/create': {'cost': 10}, 'referral/update': {'cost': 10}, 'referral/bind': {'cost': 10}, 'referral/edit_split': {'cost': 10}, 'referral/edit_referee_description': {'cost': 10}, 'referral/multi_level/admin': {'cost': 10}, 'referral/multi_level/admin/create/affiliate': {'cost': 10}, 'referral/multi_level/admin/reset/affiliate': {'cost': 10}, 'referral/multi_level/admin/update': {'cost': 10}, 'referral/multi_level/admin/update/affiliate': {'cost': 10}, 'referral/multi_level/claim_code': {'cost': 10}, 'referral/multi_level/rebate_rate/set_default': {'cost': 10}, 'referral/multi_level/rebate_rate/update': {'cost': 10}, }, 'put': { 'order': {'cost': 1}, 'algo/order': {'cost': 1}, }, 'delete': { 'order': {'cost': 1}, 'algo/order': {'cost': 1}, 'client/order': {'cost': 1}, 'algo/client/order': {'cost': 1}, 'algo/orders': {'cost': 1}, 'orders': {'cost': 1}, 'batch-order': {'cost': 1}, 'client/batch-order': {'cost': 1}, }, }, }, 'v2': { 'private': { 'post': { 'internal_transfer': {'cost': 1}, }, }, }, }, 'requiredCredentials': { 'apiKey': True, 'secret': True, 'accountId': True, 'privateKey': False, }, 'fees': { 'trading': { 'tierBased': True, 'percentage': True, 'maker': self.parse_number('0.0002'), 'taker': self.parse_number('0.0005'), }, }, 'options': { 'sandboxMode': False, 'brokerId': 'CCXT', 'verifyingContractAddress': '0x6F7a338F2aA472838dEFD3283eB360d4Dff5D203', }, 'features': { 'default': { 'sandbox': True, 'createOrder': { 'marginMode': False, 'triggerPrice': True, 'triggerPriceType': None, 'triggerDirection': False, 'stopLossPrice': False, # todo by triggerPrice 'takeProfitPrice': False, # todo by triggerPrice 'attachedStopLossTakeProfit': None, 'timeInForce': { 'IOC': True, 'FOK': True, 'PO': True, 'GTD': False, }, 'hedged': False, 'trailing': True, 'leverage': True, # todo implement 'marketBuyByCost': False, 'marketBuyRequiresPrice': False, 'selfTradePrevention': False, 'iceberg': True, # todo implement }, 'createOrders': { 'max': 10, }, 'fetchMyTrades': { 'marginMode': False, 'limit': 500, 'daysBack': None, 'untilDays': 100000, 'symbolRequired': False, }, 'fetchOrder': { 'marginMode': False, 'trigger': True, 'trailing': False, 'symbolRequired': False, }, 'fetchOpenOrders': { 'marginMode': False, 'limit': 500, 'trigger': True, 'trailing': False, 'symbolRequired': False, }, 'fetchOrders': None, 'fetchClosedOrders': { 'marginMode': False, 'limit': 500, 'daysBack': None, 'daysBackCanceled': None, 'untilDays': 100000, 'trigger': True, 'trailing': False, 'symbolRequired': False, }, 'fetchOHLCV': { 'limit': 1000, }, }, 'spot': { 'extends': 'default', }, 'forDerivatives': { 'extends': 'default', 'createOrder': { # todo: implementation needs unification 'triggerPriceType': None, 'attachedStopLossTakeProfit': { # todo: implementation needs unification 'triggerPriceType': None, 'price': False, }, }, }, 'swap': { 'linear': { 'extends': 'forDerivatives', }, 'inverse': None, }, 'future': { 'linear': None, 'inverse': None, }, }, 'commonCurrencies': {}, 'exceptions': { 'exact': { '-1000': ExchangeError, # UNKNOWN The data does not exist '-1001': AuthenticationError, # INVALID_SIGNATURE The api key or secret is in wrong format. '-1002': AuthenticationError, # UNAUTHORIZED API key or secret is invalid, it may because key have insufficient permission or the key is expired/revoked. '-1003': RateLimitExceeded, # TOO_MANY_REQUEST Rate limit exceed. '-1004': BadRequest, # UNKNOWN_PARAM An unknown parameter was sent. '-1005': BadRequest, # INVALID_PARAM Some parameters are in wrong format for api. '-1006': InvalidOrder, # RESOURCE_NOT_FOUND The data is not found in server. For example, when client try canceling a CANCELLED order, will raise this error. '-1007': BadRequest, # DUPLICATE_REQUEST The data is already exists or your request is duplicated. '-1008': InvalidOrder, # QUANTITY_TOO_HIGH The quantity of settlement is too high than you can request. '-1009': InsufficientFunds, # CAN_NOT_WITHDRAWAL Can not request withdrawal settlement, you need to deposit other arrears first. '-1011': NetworkError, # RPC_NOT_CONNECT Can not place/cancel orders, it may because internal network error. Please try again in a few seconds. '-1012': BadRequest, # RPC_REJECT The place/cancel order request is rejected by internal module, it may because the account is in liquidation or other internal errors. Please try again in a few seconds. '-1101': InsufficientFunds, # RISK_TOO_HIGH The risk exposure for client is too high, it may cause by sending too big order or the leverage is too low. please refer to client info to check the current exposure. '-1102': InvalidOrder, # MIN_NOTIONAL The order value (price * size) is too small. '-1103': InvalidOrder, # PRICE_FILTER The order price is not following the tick size rule for the symbol. '-1104': InvalidOrder, # SIZE_FILTER The order quantity is not following the step size rule for the symbol. '-1105': InvalidOrder, # PERCENTAGE_FILTER Price is X% too high or X% too low from the mid price. '-1201': BadRequest, # LIQUIDATION_REQUEST_RATIO_TOO_SMALL total notional < 10000, least req ratio should = 1 '-1202': BadRequest, # LIQUIDATION_STATUS_ERROR No need to liquidation because user margin is enough. '29': BadRequest, # {"success":false,"code":29,"message":"Verify contract is invalid"} '9': AuthenticationError, # {"success":false,"code":9,"message":"Address and signature do not match"} '3': AuthenticationError, # {"success":false,"code":3,"message":"Signature error"} '2': BadRequest, # {"success":false,"code":2,"message":"Timestamp expired"} '15': BadRequest, # {"success":false,"code":15,"message":"BrokerId is not exist"} }, 'broad': { }, }, 'precisionMode': TICK_SIZE, }) def set_sandbox_mode(self, enable: bool): super(woofipro, self).set_sandbox_mode(enable) self.options['sandboxMode'] = enable async def fetch_status(self, params: dict = {}) -> Status: """ the latest known information on the availability of the exchange API https://orderly.network/docs/build-on-omnichain/restful-api/public/get-system-maintenance-status :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `status structure ` """ response = await self.v1PublicGetPublicSystemInfo(params) # # { # "success": true, # "data": { # "status": 0, # "msg": "System is functioning properly." # }, # "timestamp": "1709274106602" # } # data = self.safe_dict(response, 'data', {}) status = self.safe_string(data, 'status') if status is None: status = 'error' elif status == '0': status = 'ok' else: status = 'maintenance' return { 'status': status, 'updated': None, 'eta': None, 'url': None, 'info': response, } async def fetch_time(self, params: dict = {}) -> Int: """ fetches the current integer timestamp in milliseconds from the exchange server https://orderly.network/docs/build-on-omnichain/restful-api/public/get-system-maintenance-status :param dict [params]: extra parameters specific to the exchange API endpoint :returns int: the current integer timestamp in milliseconds from the exchange server """ response = await self.v1PublicGetPublicSystemInfo(params) # # { # "success": true, # "data": { # "status": 0, # "msg": "System is functioning properly." # }, # "timestamp": "1709274106602" # } # return self.safe_integer(response, 'timestamp') def parse_market(self, market: dict) -> Market: # # { # "symbol": "PERP_BTC_USDC", # "quote_min": 123, # "quote_max": 100000, # "quote_tick": 0.1, # "base_min": 0.00001, # "base_max": 20, # "base_tick": 0.00001, # "min_notional": 1, # "price_range": 0.02, # "price_scope": 0.4, # "std_liquidation_fee": 0.03, # "liquidator_fee": 0.015, # "claim_insurance_fund_discount": 0.0075, # "funding_period": 8, # "cap_funding": 0.000375, # "floor_funding": -0.000375, # "interest_rate": 0.0001, # "created_time": 1684140107326, # "updated_time": 1685345968053, # "base_mmr": 0.05, # "base_imr": 0.1, # "imr_factor": 0.0002512, # "liquidation_tier": "1" # } # marketId = self.safe_string(market, 'symbol') if marketId is None: raise ExchangeError(self.id + ' parseMarket() missing marketId') parts = marketId.split('_') marketType = 'swap' baseId = self.safe_string(parts, 1) quoteId = self.safe_string(parts, 2) base = self.safe_currency_code(baseId) quote = self.safe_currency_code(quoteId) if (base is None) or (quote is None): return None settleId = self.safe_string(parts, 2) settle = self.safe_currency_code(settleId) symbol = base + '/' + quote + ':' + quote return self.safe_market_structure({ 'id': marketId, 'symbol': symbol, 'base': base, 'quote': quote, 'settle': settle, 'baseId': baseId, 'quoteId': quoteId, 'settleId': settleId, 'type': marketType, 'spot': False, 'margin': False, 'swap': True, 'future': False, 'option': False, 'active': None, 'contract': True, 'linear': True, 'inverse': False, 'contractSize': self.parse_number('1'), 'expiry': None, 'expiryDatetime': None, 'strike': None, 'optionType': None, 'precision': { 'amount': self.safe_number(market, 'base_tick'), 'price': self.safe_number(market, 'quote_tick'), }, 'limits': { 'leverage': { 'min': None, 'max': None, }, 'amount': { 'min': self.safe_number(market, 'base_min'), 'max': self.safe_number(market, 'base_max'), }, 'price': { 'min': self.safe_number(market, 'quote_min'), 'max': self.safe_number(market, 'quote_max'), }, 'cost': { 'min': self.safe_number(market, 'min_notional'), 'max': None, }, }, 'created': self.safe_integer(market, 'created_time'), 'info': market, }) async def fetch_markets(self, params: dict = {}) -> list[Market]: """ retrieves data on all markets for woofipro https://orderly.network/docs/build-on-omnichain/restful-api/public/get-available-symbols :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict[]: an array of objects representing market data """ response = await self.v1PublicGetPublicInfo(params) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "rows": [ # { # "symbol": "PERP_BTC_USDC", # "quote_min": 123, # "quote_max": 100000, # "quote_tick": 0.1, # "base_min": 0.00001, # "base_max": 20, # "base_tick": 0.00001, # "min_notional": 1, # "price_range": 0.02, # "price_scope": 0.4, # "std_liquidation_fee": 0.03, # "liquidator_fee": 0.015, # "claim_insurance_fund_discount": 0.0075, # "funding_period": 8, # "cap_funding": 0.000375, # "floor_funding": -0.000375, # "interest_rate": 0.0001, # "created_time": 1684140107326, # "updated_time": 1685345968053, # "base_mmr": 0.05, # "base_imr": 0.1, # "imr_factor": 0.0002512, # "liquidation_tier": "1" # } # ] # } # } # data = self.safe_dict(response, 'data', {}) rows = self.safe_list(data, 'rows', []) return self.parse_markets(rows) async def fetch_currencies(self, params: dict = {}) -> Currencies: """ fetches all available currencies on an exchange https://orderly.network/docs/build-on-omnichain/restful-api/public/get-supported-collateral-info#get-supported-collateral-info https://orderly.network/docs/build-on-omnichain/restful-api/public/get-supported-chains-per-builder#get-supported-chains-per-builder :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an associative dictionary of currencies """ result = {} tokenPromise = self.v1PublicGetPublicToken(params) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "rows": [{ # "token": "USDC", # "decimals": 6, # "minimum_withdraw_amount": 0.000001, # "token_hash": "0xd6aca1be9729c13d677335161321649cccae6a591554772516700f986f942eaa", # "chain_details": [{ # "chain_id": 43113, # "contract_address": "0x5d64c9cfb0197775b4b3ad9be4d3c7976e0d8dc3", # "cross_chain_withdrawal_fee": 123, # "decimals": 6, # "withdraw_fee": 2 # }] # } # ] # } # } # chainPromise = self.v1PublicGetPublicChainInfo(params) tokenResponse, chainResponse = await asyncio.gather(*[tokenPromise, chainPromise]) tokenData = self.safe_dict(tokenResponse, 'data', {}) tokenRows = self.safe_list(tokenData, 'rows', []) chainData = self.safe_dict(chainResponse, 'data', {}) chainRows = self.safe_list(chainData, 'rows', []) indexedChains = self.index_by(chainRows, 'chain_id') for i in range(0, len(tokenRows)): token = tokenRows[i] parsed = self.parse_currency({'_token': token, '_indexedChains': indexedChains}) if parsed is None: raise ExchangeError(self.id + ' fetchCurrencies() could not resolve parsed') result[parsed['code']] = parsed return result def parse_currency(self, rawCurrency: dict) -> CurrencyInterface: token = self.safe_dict(rawCurrency, '_token', {}) currencyId = self.safe_string(token, 'token') networks = self.safe_list(token, 'chain_details', []) code = self.safe_currency_code(currencyId) indexedChains = self.safe_dict(rawCurrency, '_indexedChains', {}) resultingNetworks = {} for j in range(0, len(networks)): networkEntry = networks[j] networkId = self.safe_string(networkEntry, 'chain_id') networkRow = self.safe_dict(indexedChains, networkId) networkName = self.safe_string(networkRow, 'name', networkId) networkCode = self.network_id_to_code(networkName, code) if networkCode is not None: resultingNetworks[networkCode] = { 'id': networkId, 'network': networkCode, 'limits': { 'withdraw': { 'min': None, 'max': None, }, 'deposit': { 'min': None, 'max': None, }, }, 'active': None, 'deposit': None, 'withdraw': None, 'fee': self.safe_number(networkEntry, 'withdrawal_fee'), 'precision': self.parse_number(self.parse_precision(self.safe_string(networkEntry, 'decimals'))), 'info': {'network': networkEntry, 'networkRow': networkRow}, } return self.safe_currency_structure({ 'id': currencyId, 'name': None, 'code': code, 'precision': None, 'active': None, 'fee': None, 'networks': resultingNetworks, 'deposit': None, 'withdraw': None, 'limits': { 'deposit': { 'min': None, 'max': None, }, 'withdraw': { 'min': self.safe_number(token, 'minimum_withdraw_amount'), 'max': None, }, }, 'info': token, }) def parse_token_and_fee_temp(self, item: dict, feeTokenKey: str, feeAmountKey: str): feeCost = self.safe_string(item, feeAmountKey) fee = None if feeCost is not None: feeCurrencyId = self.safe_string(item, feeTokenKey) feeCurrencyCode = self.safe_currency_code(feeCurrencyId) fee = { 'cost': feeCost, 'currency': feeCurrencyCode, } return fee def parse_trade(self, trade: dict, market: Market = None) -> Trade: # # public/market_trades # # { # "symbol": "SPOT_BTC_USDT", # "side": "SELL", # "executed_price": 46222.35, # "executed_quantity": 0.0012, # "executed_timestamp": "1683878609166" # } # # fetchOrderTrades, fetchOrder # # { # "id": "99119876", # "symbol": "SPOT_WOO_USDT", # "fee": "0.0024", # "side": "BUY", # "executed_timestamp": "1641481113084", # "order_id": "87001234", # "order_tag": "default", <-- this param only in "fetchOrderTrades" # "executed_price": "1", # "executed_quantity": "12", # "fee_asset": "WOO", # "is_maker": "1" # } # isFromFetchOrder = ('id' in trade) timestamp = self.safe_integer(trade, 'executed_timestamp') marketId = self.safe_string(trade, 'symbol') marketResolved = self.safe_market(marketId, market) symbol = marketResolved['symbol'] price = self.safe_string(trade, 'executed_price') amount = self.safe_string(trade, 'executed_quantity') order_id = self.safe_string(trade, 'order_id') fee = self.parse_token_and_fee_temp(trade, 'fee_asset', 'fee') side = self.safe_string_lower(trade, 'side') id = self.safe_string(trade, 'id') takerOrMaker = None if isFromFetchOrder: isMaker = self.safe_string(trade, 'is_maker') == '1' takerOrMaker = 'maker' if isMaker else 'taker' return self.safe_trade({ 'id': id, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'symbol': symbol, 'side': side, 'price': price, 'amount': amount, 'cost': Precise.string_mul(price, amount), 'order': order_id, 'takerOrMaker': takerOrMaker, 'type': None, 'fee': fee, 'info': trade, }, marketResolved) async def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params: dict = {}) -> list[Trade]: """ get the list of most recent trades for a particular symbol https://orderly.network/docs/build-on-omnichain/restful-api/public/get-market-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 :returns Trade[]: a list of `trade structures ` """ if self.markets is None: await self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], } if limit is not None: request['limit'] = limit response = await self.v1PublicGetPublicMarketTrades(self.extend(request, params)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "rows": [{ # "symbol": "PERP_ETH_USDC", # "side": "BUY", # "executed_price": 2050, # "executed_quantity": 1, # "executed_timestamp": 1683878609166 # }] # } # } # data = self.safe_dict(response, 'data', {}) rows = self.safe_list(data, 'rows', []) return self.parse_trades(rows, market, since, limit) def parse_funding_rate(self, fundingRate: dict, market: Market = None) -> FundingRate: # # { # "symbol":"PERP_AAVE_USDT", # "est_funding_rate":-0.00003447, # "est_funding_rate_timestamp":1653633959001, # "last_funding_rate":-0.00002094, # "last_funding_rate_timestamp":1653631200000, # "next_funding_time":1653634800000, # "sum_unitary_funding": 521.367 # } # symbol = self.safe_string(fundingRate, 'symbol') marketResolved = self.market(symbol) nextFundingTimestamp = self.safe_integer(fundingRate, 'next_funding_time') estFundingRateTimestamp = self.safe_integer(fundingRate, 'est_funding_rate_timestamp') lastFundingRateTimestamp = self.safe_integer(fundingRate, 'last_funding_rate_timestamp') fundingTimeString = self.safe_string(fundingRate, 'last_funding_rate_timestamp') nextFundingTimeString = self.safe_string(fundingRate, 'next_funding_time') millisecondsInterval = Precise.string_sub(nextFundingTimeString, fundingTimeString) return { 'info': fundingRate, 'symbol': marketResolved['symbol'], 'markPrice': None, 'indexPrice': None, 'interestRate': self.parse_number('0'), 'estimatedSettlePrice': None, 'timestamp': estFundingRateTimestamp, 'datetime': self.iso8601(estFundingRateTimestamp), 'fundingRate': self.safe_number(fundingRate, 'est_funding_rate'), 'fundingTimestamp': nextFundingTimestamp, 'fundingDatetime': self.iso8601(nextFundingTimestamp), 'nextFundingRate': None, 'nextFundingTimestamp': None, 'nextFundingDatetime': None, 'previousFundingRate': self.safe_number(fundingRate, 'last_funding_rate'), 'previousFundingTimestamp': lastFundingRateTimestamp, 'previousFundingDatetime': self.iso8601(lastFundingRateTimestamp), 'interval': self.parse_funding_interval(millisecondsInterval), } def parse_funding_interval(self, interval: Str) -> Str: intervals = { '3600000': '1h', '14400000': '4h', '28800000': '8h', '57600000': '16h', '86400000': '24h', } return self.safe_string(intervals, interval, interval) async def fetch_funding_interval(self, symbol: str, params: dict = {}) -> FundingRate: """ fetch the current funding rate interval https://orderly.network/docs/build-on-omnichain/restful-api/public/get-predicted-funding-rate-for-one-market :param str symbol: unified market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `funding rate structure ` """ return await self.fetch_funding_rate(symbol, params) async def fetch_funding_rate(self, symbol: str, params: dict = {}) -> FundingRate: """ fetch the current funding rate https://orderly.network/docs/build-on-omnichain/restful-api/public/get-predicted-funding-rate-for-one-market :param str symbol: unified market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `funding rate structure ` """ if self.markets is None: await self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], } response = await self.v1PublicGetPublicFundingRateSymbol(self.extend(request, params)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "symbol": "PERP_ETH_USDC", # "est_funding_rate": 123, # "est_funding_rate_timestamp": 1683880020000, # "last_funding_rate": 0.0001, # "last_funding_rate_timestamp": 1683878400000, # "next_funding_time": 1683907200000, # "sum_unitary_funding": 521.367 # } # } # data = self.safe_dict(response, 'data', {}) return self.parse_funding_rate(data, market) async def fetch_funding_rates(self, symbols: Strings = None, params: dict = {}) -> FundingRates: """ fetch the current funding rate for multiple markets https://orderly.network/docs/build-on-omnichain/restful-api/public/get-predicted-funding-rates-for-all-markets :param str[] symbols: unified market symbols :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict[]: an array of `funding rate structures ` """ if self.markets is None: await self.load_markets() symbolsNormalized = self.market_symbols(symbols) response = await self.v1PublicGetPublicFundingRates(params) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "rows": [{ # "symbol": "PERP_ETH_USDC", # "est_funding_rate": 123, # "est_funding_rate_timestamp": 1683880020000, # "last_funding_rate": 0.0001, # "last_funding_rate_timestamp": 1683878400000, # "next_funding_time": 1683907200000, # "sum_unitary_funding": 521.367 # }] # } # } # data = self.safe_dict(response, 'data', {}) rows = self.safe_list(data, 'rows', []) return self.parse_funding_rates(rows, symbolsNormalized) def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker: # # { # "symbol": "PERP_BTC_USDC", # "index_price": 64185.4, # "mark_price": 64171.0, # "sum_unitary_funding": 26522.3, # "est_funding_rate": 0.0001, # "last_funding_rate": 0.00010041, # "next_funding_time": 1786032000000, # "open_interest": 110.64612, # "24h_open": 64105.6, # "24h_close": 64180.0, # "24h_high": 64941.0, # "24h_low": 63837.6, # "24h_volume": 102.2817, # "24h_amount": 6595662.199482 # } # marketId = self.safe_string(ticker, 'symbol') marketResolved = self.safe_market(marketId, market) timestamp = self.safe_integer(ticker, 'timestamp') return self.safe_ticker({ 'symbol': marketResolved['symbol'], 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'high': self.safe_string(ticker, '24h_high'), 'low': self.safe_string(ticker, '24h_low'), 'bid': None, 'bidVolume': None, 'ask': None, 'askVolume': None, 'vwap': None, 'open': self.safe_string(ticker, '24h_open'), 'close': self.safe_string(ticker, '24h_close'), 'last': self.safe_string(ticker, '24h_close'), 'previousClose': None, 'change': None, 'percentage': None, 'average': None, 'baseVolume': self.safe_string(ticker, '24h_volume'), 'quoteVolume': self.safe_string(ticker, '24h_amount'), 'indexPrice': self.safe_string(ticker, 'index_price'), 'markPrice': self.safe_string(ticker, 'mark_price'), 'info': ticker, }, marketResolved) async def fetch_ticker(self, symbol: str, params: dict = {}) -> Ticker: """ fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market https://orderly.network/docs/build-on-omnichain/restful-api/public/get-market-info-for-one-symbol :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 ` """ if self.markets is None: await self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], } response = await self.v1PublicGetPublicFuturesSymbol(self.extend(request, params)) # # { # "success": true, # "timestamp": 1786022130191, # "data": { # "symbol": "PERP_BTC_USDC", # "index_price": 64185.4, # "mark_price": 64171.0, # "sum_unitary_funding": 26522.3, # "est_funding_rate": 0.0001, # "last_funding_rate": 0.00010041, # "next_funding_time": 1786032000000, # "open_interest": 110.64612, # "24h_open": 64105.6, # "24h_close": 64180.0, # "24h_high": 64941.0, # "24h_low": 63837.6, # "24h_volume": 102.2817, # "24h_amount": 6595662.199482 # } # } # data = self.safe_dict(response, 'data', {}) data['timestamp'] = self.safe_integer(response, 'timestamp') return self.parse_ticker(data, market) async def fetch_tickers(self, symbols: Strings = None, params: dict = {}) -> Tickers: """ fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market https://orderly.network/docs/build-on-omnichain/restful-api/public/get-market-info-for-all-symbols :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 ` """ if self.markets is None: await self.load_markets() symbolsNormalized = self.market_symbols(symbols) response = await self.v1PublicGetPublicFutures(params) # # { # "success": true, # "timestamp": 1786022130191, # "data": { # "rows": [{ # "symbol": "PERP_BTC_USDC", # "index_price": 64185.4, # "mark_price": 64171.0, # "sum_unitary_funding": 26522.3, # "est_funding_rate": 0.0001, # "last_funding_rate": 0.00010041, # "next_funding_time": 1786032000000, # "open_interest": 110.64612, # "24h_open": 64105.6, # "24h_close": 64180.0, # "24h_high": 64941.0, # "24h_low": 63837.6, # "24h_volume": 102.2817, # "24h_amount": 6595662.199482 # }] # } # } # data = self.safe_dict(response, 'data', {}) rows = self.safe_list(data, 'rows', []) timestamp = self.safe_integer(response, 'timestamp') result = [] for i in range(0, len(rows)): row = rows[i] marketId = self.safe_string(row, 'symbol', '') if (self.markets_by_id is None) or not (marketId in self.markets_by_id): continue # the endpoint returns entries for markets missing from public/info, e.g. pre-TGE symbols ticker = self.extend({'timestamp': timestamp}, row) result.append(self.parse_ticker(ticker)) return self.filter_by_array_tickers(result, 'symbol', symbolsNormalized) def parse_open_interest(self, interest: dict, market: Market = None) -> OpenInterest: # # { # "symbol": "PERP_BTC_USDC", # "index_price": 64185.4, # "mark_price": 64171.0, # "open_interest": 110.64612, # "24h_open": 64105.6, # "24h_close": 64180.0, # "24h_high": 64941.0, # "24h_low": 63837.6, # "24h_volume": 102.2817, # "24h_amount": 6595662.199482 # } # marketId = self.safe_string(interest, 'symbol') marketResolved = self.safe_market(marketId, market) timestamp = self.safe_integer(interest, 'timestamp') amount = self.safe_number_2(interest, 'open_interest', 'openInterest') return self.safe_open_interest({ 'symbol': marketResolved['symbol'], 'openInterestAmount': amount, 'openInterestValue': None, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'info': interest, }, marketResolved) async def fetch_open_interest(self, symbol: str, params: dict = {}) -> OpenInterest: """ retrieves the open interest of a contract trading pair https://orderly.network/docs/build-on-omnichain/restful-api/public/get-market-info-for-one-symbol :param str symbol: unified CCXT market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an `open interest structure ` """ if self.markets is None: await self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], } response = await self.v1PublicGetPublicFuturesSymbol(self.extend(request, params)) # # { # "success": true, # "timestamp": 1786022130191, # "data": { # "symbol": "PERP_BTC_USDC", # "index_price": 64185.4, # "mark_price": 64171.0, # "open_interest": 110.64612, # "24h_volume": 102.2817, # "24h_amount": 6595662.199482 # } # } # data = self.safe_dict(response, 'data', {}) data['timestamp'] = self.safe_integer(response, 'timestamp') return self.parse_open_interest(data, market) async def fetch_open_interests(self, symbols: Strings = None, params: dict = {}) -> OpenInterests: """ retrieves the open interest for a list of contract trading pairs https://orderly.network/docs/build-on-omnichain/restful-api/public/get-market-info-for-all-symbols :param str[] [symbols]: a list of unified CCXT market symbols :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a dictionary of `open interest structures ` """ if self.markets is None: await self.load_markets() symbolsNormalized = self.market_symbols(symbols) response = await self.v1PublicGetPublicFutures(params) # # { # "success": true, # "timestamp": 1786022130191, # "data": { # "rows": [{ # "symbol": "PERP_BTC_USDC", # "index_price": 64185.4, # "mark_price": 64171.0, # "open_interest": 110.64612, # "24h_volume": 102.2817, # "24h_amount": 6595662.199482 # }] # } # } # data = self.safe_dict(response, 'data', {}) rows = self.safe_list(data, 'rows', []) timestamp = self.safe_integer(response, 'timestamp') result = [] for i in range(0, len(rows)): row = rows[i] marketId = self.safe_string(row, 'symbol', '') if (self.markets_by_id is None) or not (marketId in self.markets_by_id): continue # the endpoint returns entries for markets missing from public/info, e.g. pre-TGE symbols interest = self.extend({'timestamp': timestamp}, row) result.append(self.parse_open_interest(interest)) return self.index_by(self.filter_by_array(result, 'symbol', symbolsNormalized, False), 'symbol') async def fetch_funding_rate_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[FundingRateHistory]: """ fetches historical funding rate prices https://orderly.network/docs/build-on-omnichain/restful-api/public/get-funding-rate-history-for-one-market :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 ` to fetch :param dict [params]: extra parameters specific to the exchange API endpoint :param int [params.until]: timestamp in ms of the latest funding rate :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 ` """ if self.markets is None: await self.load_markets() paginate, paramsPaginate = self.handle_option_bool_and_params(params, 'fetchFundingRateHistory', 'paginate', False) if paginate: return await self.fetch_paginated_call_incremental('fetchFundingRateHistory', symbol, since, limit, paramsPaginate, 'page', 25) request = {} symbolResolved = None if symbol is not None: market = self.market(symbol) symbolResolved = self.safe_string(market, 'symbol') request['symbol'] = market['id'] if since is not None: request['start_t'] = since requestUntil, paramsUntil = self.handle_until_option('end_t', request, paramsPaginate, 0.001) response = await self.v1PublicGetPublicFundingRateHistory(self.extend(requestUntil, paramsUntil)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "rows": [{ # "symbol": "PERP_ETH_USDC", # "funding_rate": 0.0001, # "funding_rate_timestamp": 1684224000000, # "next_funding_time": 1684252800000 # }], # "meta": { # "total": 9, # "records_per_page": 25, # "current_page": 1 # } # } # } # data = self.safe_dict(response, 'data', {}) result = self.safe_list(data, 'rows', []) rates = [] for i in range(0, len(result)): entry = result[i] marketId = self.safe_string(entry, 'symbol') timestamp = self.safe_integer(entry, 'funding_rate_timestamp') rates.append({ 'info': entry, 'symbol': self.safe_symbol(marketId), 'fundingRate': self.safe_number(entry, 'funding_rate'), 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), }) sorted = self.sort_by(rates, 'timestamp') return self.filter_by_symbol_since_limit(sorted, symbolResolved, since, limit) def parse_income(self, income: dict, market: Market = None) -> object: # # { # "symbol": "PERP_ETH_USDC", # "funding_rate": 0.00046875, # "mark_price": 2100, # "funding_fee": 0.000016, # "payment_type": "Pay", # "status": "Accrued", # "created_time": 1682235722003, # "updated_time": 1682235722003 # } # marketId = self.safe_string(income, 'symbol') symbol = self.safe_symbol(marketId, market) amount = self.safe_string(income, 'funding_fee') code = self.safe_currency_code('USDC') timestamp = self.safe_integer(income, 'updated_time') rate = self.safe_number(income, 'funding_rate') paymentType = self.safe_string(income, 'payment_type') amount = Precise.string_neg(amount) if (paymentType == 'Pay') else amount return { 'info': income, 'symbol': symbol, 'code': code, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'id': None, 'amount': self.parse_number(amount), 'rate': rate, } async def fetch_funding_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[FundingHistory]: """ fetch the history of funding payments paid and received on self account https://orderly.network/docs/build-on-omnichain/restful-api/private/get-funding-fee-history :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 :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 `funding history structure ` """ if self.markets is None: await self.load_markets() paginate, paramsPaginate = self.handle_option_bool_and_params(params, 'fetchFundingHistory', 'paginate', False) if paginate: return await self.fetch_paginated_call_incremental('fetchFundingHistory', symbol, since, limit, paramsPaginate, 'page', 500) request = {} market = None if symbol is not None: market = self.market(symbol) request['symbol'] = market['id'] if since is not None: request['start_t'] = since until = self.safe_integer(paramsPaginate, 'until') # unified in milliseconds paramsOmitted = self.omit(paramsPaginate, ['until']) if until is not None: request['end_t'] = until if limit is not None: request['size'] = min(limit, 500) response = await self.v1PrivateGetFundingFeeHistory(self.extend(request, paramsOmitted)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "meta": { # "total": 9, # "records_per_page": 25, # "current_page": 1 # }, # "rows": [{ # "symbol": "PERP_ETH_USDC", # "funding_rate": 0.00046875, # "mark_price": 2100, # "funding_fee": 0.000016, # "payment_type": "Pay", # "status": "Accrued", # "created_time": 1682235722003, # "updated_time": 1682235722003 # }] # } # } # data = self.safe_dict(response, 'data', {}) rows = self.safe_list(data, 'rows', []) return self.parse_incomes(rows, market, since, limit) async def fetch_trading_fees(self, params: dict = {}) -> TradingFees: """ fetch the trading fees for multiple markets https://orderly.network/docs/build-on-omnichain/restful-api/private/get-account-information :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a dictionary of `fee structures ` indexed by market symbols """ if self.markets is None: await self.load_markets() response = await self.v1PrivateGetClientInfo(params) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "account_id": "", # "email": "test@test.com", # "account_mode": "FUTURES", # "max_leverage": 20, # "taker_fee_rate": 123, # "maker_fee_rate": 123, # "futures_taker_fee_rate": 123, # "futures_maker_fee_rate": 123, # "maintenance_cancel_orders": true, # "imr_factor": { # "PERP_BTC_USDC": 123, # "PERP_ETH_USDC": 123, # "PERP_NEAR_USDC": 123 # }, # "max_notional": { # "PERP_BTC_USDC": 123, # "PERP_ETH_USDC": 123, # "PERP_NEAR_USDC": 123 # } # } # } # data = self.safe_dict(response, 'data', {}) maker = self.safe_string(data, 'futures_maker_fee_rate') taker = self.safe_string(data, 'futures_taker_fee_rate') result = {} symbols = self.symbols for i in range(0, len(symbols)): symbol = symbols[i] result[symbol] = { 'info': response, 'symbol': symbol, 'maker': self.parse_number(Precise.string_div(maker, '10000')), 'taker': self.parse_number(Precise.string_div(taker, '10000')), 'percentage': True, 'tierBased': True, } return result async def fetch_order_book(self, symbol: str, limit: Int = None, params: dict = {}) -> OrderBook: """ fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data https://orderly.network/docs/build-on-omnichain/restful-api/private/orderbook-snapshot :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 :returns dict: an `order book structure ` """ if self.markets is None: await self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], } if limit is not None: request['max_level'] = min(limit, 1000) response = await self.v1PrivateGetOrderbookSymbol(self.extend(request, params)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "asks": [{ # "price": 10669.4, # "quantity": 1.56263218 # }], # "bids": [{ # "price": 10669.4, # "quantity": 1.56263218 # }], # "timestamp": 123 # } # } # data = self.safe_dict(response, 'data', {}) timestamp = self.safe_integer(data, 'timestamp') return self.parse_order_book(data, symbol, timestamp, 'bids', 'asks', 'price', 'quantity') def parse_ohlcv(self, ohlcv: object, market: Market = None) -> list: return [ self.safe_integer(ohlcv, 'start_timestamp'), self.safe_number(ohlcv, 'open'), self.safe_number(ohlcv, 'high'), self.safe_number(ohlcv, 'low'), self.safe_number(ohlcv, 'close'), self.safe_number(ohlcv, 'volume'), ] async def fetch_ohlcv(self, symbol: str, timeframe: str = '1m', since: Int = None, limit: Int = None, params: dict = {}) -> list[list]: """ https://orderly.network/docs/build-on-omnichain/restful-api/public/get-kline fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market :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]: max=1000, max=100 when since is defined and is less than(now - (999 * (timeframe in ms))) :param dict [params]: extra parameters specific to the exchange API endpoint :returns int[][]: A list of candles ordered as timestamp, open, high, low, close, volume """ if self.markets is None: await self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], 'type': self.safe_string(self.timeframes, timeframe, timeframe), } if limit is not None: request['limit'] = min(limit, 1000) response = await self.v1PrivateGetKline(self.extend(request, params)) data = self.safe_dict(response, 'data', {}) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "rows": [{ # "open": 66166.23, # "close": 66124.56, # "low": 66038.06, # "high": 66176.97, # "volume": 23.45528526, # "amount": 1550436.21725288, # "symbol": "PERP_BTC_USDC", # "type": "1m", # "start_timestamp": 1636388220000, # "end_timestamp": 1636388280000 # }] # } # } # rows = self.safe_list(data, 'rows', []) return self.parse_ohlcvs(rows, market, timeframe, since, limit) def parse_order(self, order: dict, market: Market = None) -> Order: # # Possible input functions: # * createOrder # * createOrders # * cancelOrder # * fetchOrder # * fetchOrders # const isFromFetchOrder = ('order_tag' in order); TO_DO # # stop order after creating it: # { # "orderId": "1578938", # "clientOrderId": "0", # "algoType": "STOP_LOSS", # "quantity": "0.1" # } # stop order after fetching it: # { # "algoOrderId": "1578958", # "clientOrderId": "0", # "rootAlgoOrderId": "1578958", # "parentAlgoOrderId": "0", # "symbol": "SPOT_LTC_USDT", # "orderTag": "default", # "algoType": "STOP_LOSS", # "side": "BUY", # "quantity": "0.1", # "isTriggered": false, # "triggerPrice": "100", # "triggerStatus": "USELESS", # "type": "LIMIT", # "rootAlgoStatus": "CANCELLED", # "algoStatus": "CANCELLED", # "triggerPriceType": "MARKET_PRICE", # "price": "75", # "triggerTime": "0", # "totalExecutedQuantity": "0", # "averageExecutedPrice": "0", # "totalFee": "0", # "feeAsset": '', # "reduceOnly": false, # "createdTime": "1686149609.744", # "updatedTime": "1686149903.362" # } # timestamp = self.safe_integer_n(order, ['timestamp', 'created_time', 'createdTime']) orderId = self.safe_string_n(order, ['order_id', 'orderId', 'algoOrderId']) clientOrderId = self.omit_zero(self.safe_string_2(order, 'client_order_id', 'clientOrderId')) # Somehow, this always returns 0 for limit order marketId = self.safe_string(order, 'symbol') marketResolved = self.safe_market(marketId, market) symbol = marketResolved['symbol'] price = self.safe_string_2(order, 'order_price', 'price') amount = self.safe_string_2(order, 'order_quantity', 'quantity') # This is base amount cost = self.safe_string_2(order, 'order_amount', 'amount') # This is quote amount orderType = self.safe_string_lower_2(order, 'order_type', 'type') status = self.safe_string_2(order, 'status', 'algoStatus') success = self.safe_bool(order, 'success') if success is not None: status = 'NEW' if (success) else 'REJECTED' side = self.safe_string_lower(order, 'side') filled = self.safe_string_n(order, ['total_executed_quantity', 'totalExecutedQuantity', 'executed_quantity', 'executed']) average = self.omit_zero(self.safe_string_2(order, 'average_executed_price', 'averageExecutedPrice')) fee = self.safe_value_2(order, 'total_fee', 'totalFee') feeCurrency = self.safe_string_2(order, 'fee_asset', 'feeAsset') transactions = self.safe_list(order, 'Transactions') triggerPrice = self.safe_number(order, 'triggerPrice') takeProfitPrice = None stopLossPrice = None childOrders = self.safe_list(order, 'childOrders') if childOrders is not None: first = self.safe_dict(childOrders, 0) innerChildOrders = self.safe_list(first, 'childOrders', []) innerChildOrdersLength = len(innerChildOrders) if innerChildOrdersLength > 0: takeProfitOrder = self.safe_dict(innerChildOrders, 0) stopLossOrder = self.safe_dict(innerChildOrders, 1) takeProfitPrice = self.safe_number(takeProfitOrder, 'triggerPrice') stopLossPrice = self.safe_number(stopLossOrder, 'triggerPrice') lastUpdateTimestamp = self.safe_integer_2(order, 'updatedTime', 'updated_time') return self.safe_order({ 'id': orderId, 'clientOrderId': clientOrderId, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'lastTradeTimestamp': None, 'lastUpdateTimestamp': lastUpdateTimestamp, 'status': self.parse_order_status(status), 'symbol': symbol, 'type': self.parse_order_type(orderType), 'timeInForce': self.parse_time_in_force(orderType), 'postOnly': None, # TO_DO 'reduceOnly': self.safe_bool(order, 'reduce_only'), 'side': side, 'price': price, 'triggerPrice': triggerPrice, 'takeProfitPrice': takeProfitPrice, 'stopLossPrice': stopLossPrice, 'average': average, 'amount': amount, 'filled': filled, 'remaining': Precise.string_sub(amount, filled), # TO_DO 'cost': cost, 'trades': transactions, 'fee': { 'cost': fee, 'currency': feeCurrency, }, 'info': order, }, marketResolved) def parse_time_in_force(self, timeInForce: Str) -> Str: timeInForces = { 'ioc': 'IOC', 'fok': 'FOK', 'post_only': 'PO', } return self.safe_string(timeInForces, timeInForce) def parse_order_status(self, status: Str) -> Str: if status is not None: statuses = { 'NEW': 'open', 'FILLED': 'closed', 'CANCEL_SENT': 'canceled', 'CANCEL_ALL_SENT': 'canceled', 'CANCELLED': 'canceled', 'PARTIAL_FILLED': 'open', 'REJECTED': 'rejected', 'INCOMPLETE': 'open', 'COMPLETED': 'closed', } return self.safe_string(statuses, status, status) return None def parse_order_type(self, type: Str) -> Str: types = { 'LIMIT': 'limit', 'MARKET': 'market', 'POST_ONLY': 'limit', } return self.safe_string_lower(types, type, type) def create_order_request(self, symbol: Str, type: Str, side: Str, amount: Num, price: Num = None, params: dict = {}) -> dict: if type is None: raise ArgumentsRequired(self.id + ' requires a type argument') if side is None: raise ArgumentsRequired(self.id + ' requires a side argument') """ @ignore helper function to build the request :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 you want to trade in units of the base currency :param float [price]: the price that 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 :returns dict: request to be sent to the exchange """ reduceOnly = self.safe_bool_2(params, 'reduceOnly', 'reduce_only') orderType = type.upper() if side is None: raise ArgumentsRequired(self.id + ' createOrderRequest() requires a side argument') market = self.market(symbol) orderSide = side.upper() request = { 'symbol': market['id'], 'side': orderSide, } triggerPrice = self.safe_string_2(params, 'triggerPrice', 'stopPrice') stopLoss = self.safe_dict(params, 'stopLoss') takeProfit = self.safe_dict(params, 'takeProfit') hasStopLoss = (stopLoss is not None) hasTakeProfit = (takeProfit is not None) algoType = self.safe_string(params, 'algoType') paramsChildOrders = self.safe_list(params, 'childOrders') isConditional = triggerPrice is not None or hasStopLoss or hasTakeProfit or (paramsChildOrders is not None) isMarket = orderType == 'MARKET' timeInForce = self.safe_string_lower(params, 'timeInForce') postOnly = self.is_post_only(isMarket, None, params) orderQtyKey = 'quantity' if isConditional else 'order_quantity' priceKey = 'price' if isConditional else 'order_price' typeKey = 'type' if isConditional else 'order_type' request[typeKey] = orderType # LIMIT/MARKET/IOC/FOK/POST_ONLY/ASK/BID if not isConditional: if postOnly: request['order_type'] = 'POST_ONLY' elif timeInForce == 'fok': request['order_type'] = 'FOK' elif timeInForce == 'ioc': request['order_type'] = 'IOC' if reduceOnly is True: request['reduce_only'] = reduceOnly if price is not None: request[priceKey] = self.price_to_precision(symbol, price) if isMarket and not isConditional: request[orderQtyKey] = self.amount_to_precision(symbol, amount) elif algoType != 'POSITIONAL_TP_SL': request[orderQtyKey] = self.amount_to_precision(symbol, amount) clientOrderId = self.safe_string_n(params, ['clOrdID', 'clientOrderId', 'client_order_id']) if clientOrderId is not None: request['client_order_id'] = clientOrderId if triggerPrice is not None: request['trigger_price'] = self.price_to_precision(symbol, triggerPrice) request['algo_type'] = 'STOP' elif hasStopLoss or hasTakeProfit: request['algo_type'] = 'TP_SL' childOrders = [] closeSide = 'SELL' if (orderSide == 'BUY') else 'BUY' if hasStopLoss: stopLossPrice = self.safe_value_2(stopLoss, 'triggerPrice', 'price', stopLoss) stopLossOrder = { 'side': closeSide, 'algo_type': 'TP_SL', 'trigger_price': self.price_to_precision(symbol, stopLossPrice), 'type': 'LIMIT', 'reduce_only': True, } childOrders.append(stopLossOrder) if hasTakeProfit: takeProfitPrice = self.safe_value_2(takeProfit, 'triggerPrice', 'price', takeProfit) takeProfitOrder = { 'side': closeSide, 'algo_type': 'TP_SL', 'trigger_price': self.price_to_precision(symbol, takeProfitPrice), 'type': 'LIMIT', 'reduce_only': True, } childOrders.append(takeProfitOrder) outterOrder = { 'symbol': market['id'], 'reduce_only': False, 'algo_type': 'POSITIONAL_TP_SL', 'child_orders': childOrders, } request['child_orders'] = [outterOrder] paramsOmitted = self.omit(params, ['reduceOnly', 'reduce_only', 'clOrdID', 'clientOrderId', 'client_order_id', 'postOnly', 'timeInForce', 'stopPrice', 'triggerPrice', 'stopLoss', 'takeProfit']) return self.extend(request, paramsOmitted) async def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params: dict = {}) -> Order: """ create a trade order https://orderly.network/docs/build-on-omnichain/restful-api/private/create-order https://orderly.network/docs/build-on-omnichain/restful-api/private/create-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 float [params.triggerPrice]: The price a trigger order is triggered at :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 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.algoType]: 'STOP'or 'TP_SL' or 'POSITIONAL_TP_SL' :param float [params.cost]: *spot market buy only* the quote quantity that can be used as an alternative for the amount :param str [params.clientOrderId]: a unique id for the order :returns dict: an `order structure ` """ if self.markets is None: await self.load_markets() market = self.market(symbol) request = self.create_order_request(symbol, type, side, amount, price, params) triggerPrice = self.safe_string_2(params, 'triggerPrice', 'stopPrice') stopLoss = self.safe_dict(params, 'stopLoss') takeProfit = self.safe_dict(params, 'takeProfit') paramsChildOrders = self.safe_list(params, 'childOrders') isConditional = triggerPrice is not None or stopLoss is not None or takeProfit is not None or (paramsChildOrders is not None) response = None if isConditional: response = await self.v1PrivatePostAlgoOrder(request) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "order_id": 13, # "client_order_id": "testclientid", # "algo_type": "STOP", # "quantity": 100.12 # } # } # else: response = await self.v1PrivatePostOrder(request) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "order_id": 13, # "client_order_id": "testclientid", # "order_type": "LIMIT", # "order_price": 100.12, # "order_quantity": 0.987654, # "order_amount": 0.8, # "error_message": "none" # } # } # data = self.safe_dict(response, 'data', {}) data['timestamp'] = self.safe_integer(response, 'timestamp') order = self.parse_order(data, market) order['type'] = type return order async def create_orders(self, orders: list[OrderRequest], params: dict = {}) -> list[Order]: """ *contract only* create a list of trade orders https://orderly.network/docs/build-on-omnichain/restful-api/private/batch-create-order :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 ` """ if self.markets is None: await self.load_markets() ordersRequests = [] for i in range(0, len(orders)): rawOrder = self.safe_dict(orders, i) marketId = self.safe_string(rawOrder, 'symbol') type = self.safe_string(rawOrder, 'type') side = self.safe_string(rawOrder, 'side') amount = self.safe_value(rawOrder, 'amount') price = self.safe_value(rawOrder, 'price') orderParams = self.safe_dict(rawOrder, 'params', {}) triggerPrice = self.safe_string_2(orderParams, 'triggerPrice', 'stopPrice') stopLoss = self.safe_dict(orderParams, 'stopLoss') takeProfit = self.safe_dict(orderParams, 'takeProfit') paramsChildOrders = self.safe_list(orderParams, 'childOrders') isConditional = triggerPrice is not None or stopLoss is not None or takeProfit is not None or (paramsChildOrders is not None) if isConditional: raise NotSupported(self.id + ' createOrders() only support non-stop order') orderRequest = self.create_order_request(marketId, type, side, amount, price, orderParams) ordersRequests.append(orderRequest) request = { 'orders': ordersRequests, } response = await self.v1PrivatePostBatchOrder(self.extend(request, params)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "rows": [{ # "order_id": 13, # "client_order_id": "testclientid", # "order_type": "LIMIT", # "order_price": 100.12, # "order_quantity": 0.987654, # "order_amount": 0.8, # "error_message": "none" # }] # } # } # data = self.safe_dict(response, 'data', {}) rows = self.safe_list(data, 'rows', []) return self.parse_orders(rows) async def edit_order(self, id: str, symbol: str, type: OrderType, side: OrderSide, amount: Num = None, price: Num = None, params: dict = {}) -> Order: """ edit a trade order https://orderly.network/docs/build-on-omnichain/restful-api/private/edit-order https://orderly.network/docs/build-on-omnichain/restful-api/private/edit-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 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 float [params.triggerPrice]: The price a trigger order is triggered at :param float [params.stopLossPrice]: price to trigger stop-loss orders :param float [params.takeProfitPrice]: price to trigger take-profit orders :returns dict: an `order structure ` """ if self.markets is None: await self.load_markets() market = self.market(symbol) request = { 'order_id': id, } triggerPrice = self.safe_string_n(params, ['triggerPrice', 'stopPrice', 'takeProfitPrice', 'stopLossPrice']) if triggerPrice is not None: request['triggerPrice'] = self.price_to_precision(symbol, triggerPrice) paramsChildOrders = self.safe_list(params, 'childOrders') isConditional = (triggerPrice is not None) or (paramsChildOrders is not None) orderQtyKey = 'quantity' if isConditional else 'order_quantity' priceKey = 'price' if isConditional else 'order_price' if price is not None: request[priceKey] = self.price_to_precision(symbol, price) if amount is not None: request[orderQtyKey] = self.amount_to_precision(symbol, amount) paramsOmitted = self.omit(params, ['stopPrice', 'triggerPrice', 'takeProfitPrice', 'stopLossPrice', 'trailingTriggerPrice', 'trailingAmount', 'trailingPercent']) response = None self.check_required_argument('editOrder', side, 'side') if isConditional: response = await self.v1PrivatePutAlgoOrder(self.extend(request, paramsOmitted)) else: request['symbol'] = market['id'] request['side'] = side.upper() orderType = type.upper() timeInForce = self.safe_string_lower(paramsOmitted, 'timeInForce') isMarket = orderType == 'MARKET' postOnly = self.is_post_only(isMarket, None, paramsOmitted) if postOnly: request['order_type'] = 'POST_ONLY' elif timeInForce == 'fok': request['order_type'] = 'FOK' elif timeInForce == 'ioc': request['order_type'] = 'IOC' else: request['order_type'] = orderType clientOrderId = self.safe_string_n(paramsOmitted, ['clOrdID', 'clientOrderId', 'client_order_id']) paramsOmitted2 = self.omit(paramsOmitted, ['clOrdID', 'clientOrderId', 'client_order_id', 'postOnly', 'timeInForce']) if clientOrderId is not None: request['client_order_id'] = clientOrderId # request['side'] = side.toUpperCase (); # request['symbol'] = market['id']; response = await self.v1PrivatePutOrder(self.extend(request, paramsOmitted2)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "status": "EDIT_SENT" # } # } # data = self.safe_dict(response, 'data', {}) data['timestamp'] = self.safe_integer(response, 'timestamp') return self.parse_order(data, market) async def cancel_order(self, id: str, symbol: Str = None, params: dict = {}) -> Order: """ https://orderly.network/docs/build-on-omnichain/restful-api/private/cancel-order https://orderly.network/docs/build-on-omnichain/restful-api/private/cancel-order-by-client_order_id https://orderly.network/docs/build-on-omnichain/restful-api/private/cancel-algo-order https://orderly.network/docs/build-on-omnichain/restful-api/private/cancel-algo-order-by-client_order_id cancels an open 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]: whether the order is a stop/algo order :param str [params.clientOrderId]: a unique id for the order :returns dict: An `order structure ` """ trigger = self.safe_bool_2(params, 'stop', 'trigger', False) paramsOmitted = self.omit(params, ['stop', 'trigger']) if (not trigger) and (symbol is None): raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument') if self.markets is None: await self.load_markets() market = None if symbol is not None: market = self.market(symbol) request = { 'symbol': self.safe_string(market, 'id'), } clientOrderIdUnified = self.safe_string_2(paramsOmitted, 'clOrdID', 'clientOrderId') clientOrderIdExchangeSpecific = self.safe_string(paramsOmitted, 'client_order_id', clientOrderIdUnified) isByClientOrder = clientOrderIdExchangeSpecific is not None response = None if trigger: if isByClientOrder: request['client_order_id'] = clientOrderIdExchangeSpecific paramsOmitted2 = self.omit(paramsOmitted, ['clOrdID', 'clientOrderId', 'client_order_id']) response = await self.v1PrivateDeleteAlgoClientOrder(self.extend(request, paramsOmitted2)) else: request['order_id'] = id response = await self.v1PrivateDeleteAlgoOrder(self.extend(request, paramsOmitted)) else: if isByClientOrder: request['client_order_id'] = clientOrderIdExchangeSpecific paramsOmitted3 = self.omit(paramsOmitted, ['clOrdID', 'clientOrderId', 'client_order_id']) response = await self.v1PrivateDeleteClientOrder(self.extend(request, paramsOmitted3)) else: request['order_id'] = id response = await self.v1PrivateDeleteOrder(self.extend(request, paramsOmitted)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "status": "CANCEL_SENT" # } # } # # { # "success": true, # "timestamp": 1702989203989, # "status": "CANCEL_SENT" # } # extendParams = {'symbol': symbol} if isByClientOrder: extendParams['client_order_id'] = clientOrderIdExchangeSpecific else: extendParams['id'] = id if trigger: parsedResponse = {} if (response is None) else response return self.extend(self.parse_order(parsedResponse), extendParams) data = self.safe_dict(response, 'data', {}) return self.extend(self.parse_order(data), extendParams) async def cancel_orders(self, ids: list[str], symbol: Str = None, params: dict = {}) -> list[Order]: """ cancel multiple orders https://orderly.network/docs/build-on-omnichain/restful-api/private/batch-cancel-orders https://orderly.network/docs/build-on-omnichain/restful-api/private/batch-cancel-orders-by-client_order_id :param str[] ids: order ids :param str [symbol]: unified market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :param str[] [params.client_order_ids]: max length 10 e.g. ["my_id_1","my_id_2"], encode the double quotes. No space after comma :returns dict: an list of `order structures ` """ if self.markets is None: await self.load_markets() clientOrderIds = self.safe_list_n(params, ['clOrdIDs', 'clientOrderIds', 'client_order_ids']) paramsOmitted = self.omit(params, ['clOrdIDs', 'clientOrderIds', 'client_order_ids']) request = {} response = None if clientOrderIds is not None: request['client_order_ids'] = ','.join(clientOrderIds) response = await self.v1PrivateDeleteClientBatchOrder(self.extend(request, paramsOmitted)) else: request['order_ids'] = ','.join(ids) response = await self.v1PrivateDeleteBatchOrder(self.extend(request, paramsOmitted)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "status": "CANCEL_ALL_SENT" # } # } # return [self.safe_order({ 'info': response, })] async def cancel_all_orders(self, symbol: Str = None, params: dict = {}) -> list[Order]: """ https://orderly.network/docs/build-on-omnichain/restful-api/private/cancel-all-pending-algo-orders https://orderly.network/docs/build-on-omnichain/restful-api/private/cancel-all-pending-orders cancel all open orders in a market :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/algo order :returns dict: an list of `order structures ` """ if self.markets is None: await self.load_markets() trigger = self.safe_bool_2(params, 'stop', 'trigger') paramsOmitted = self.omit(params, ['stop', 'trigger']) request = {} if symbol is not None: market = self.market(symbol) request['symbol'] = market['id'] response = None if trigger is True: response = await self.v1PrivateDeleteAlgoOrders(self.extend(request, paramsOmitted)) else: response = await self.v1PrivateDeleteOrders(self.extend(request, paramsOmitted)) # trigger # { # "success": true, # "timestamp": 1702989203989, # "status": "CANCEL_ALL_SENT" # } # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "status": "CANCEL_ALL_SENT" # } # } # return [ self.safe_order({ 'info': response, }), ] async def fetch_order(self, id: str, symbol: Str = None, params: dict = {}) -> Order: """ https://orderly.network/docs/build-on-omnichain/restful-api/private/get-order-by-order_id https://orderly.network/docs/build-on-omnichain/restful-api/private/get-order-by-client_order_id https://orderly.network/docs/build-on-omnichain/restful-api/private/get-algo-order-by-order_id https://orderly.network/docs/build-on-omnichain/restful-api/private/get-algo-order-by-client_order_id fetches information on an order made by the user :param str id: the 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]: whether the order is a stop/algo order :param str [params.clientOrderId]: a unique id for the order :returns dict: An `order structure ` """ if self.markets is None: await self.load_markets() market = None if symbol is not None: market = self.market(symbol) trigger = self.safe_bool_2(params, 'stop', 'trigger', False) request = {} clientOrderId = self.safe_string_n(params, ['clOrdID', 'clientOrderId', 'client_order_id']) paramsOmitted = self.omit(params, ['stop', 'trigger', 'clOrdID', 'clientOrderId', 'client_order_id']) response = None if trigger: if clientOrderId is not None and clientOrderId != '': request['client_order_id'] = clientOrderId response = await self.v1PrivateGetAlgoClientOrderClientOrderId(self.extend(request, paramsOmitted)) else: request['oid'] = id response = await self.v1PrivateGetAlgoOrderOid(self.extend(request, paramsOmitted)) else: if (clientOrderId is not None) and (clientOrderId != ''): request['client_order_id'] = clientOrderId response = await self.v1PrivateGetClientOrderClientOrderId(self.extend(request, paramsOmitted)) else: request['oid'] = id response = await self.v1PrivateGetOrderOid(self.extend(request, paramsOmitted)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "order_id": 78151, # "user_id": 12345, # "price": 0.67772, # "type": "LIMIT", # "quantity": 20, # "amount": 10, # "executed_quantity": 20, # "total_executed_quantity": 20, # "visible_quantity": 1, # "symbol": "PERP_WOO_USDC", # "side": "BUY", # "status": "FILLED", # "total_fee": 0.5, # "fee_asset": "WOO", # "client_order_id": 1, # "average_executed_price": 0.67772, # "created_time": 1653563963000, # "updated_time": 1653564213000, # "realized_pnl": 123 # } # } # parsedOrders = self.safe_dict(response, 'data', response) if parsedOrders is None: parsedOrders = {} return self.parse_order(parsedOrders, market) async def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Order]: """ fetches information on multiple orders made by the user https://orderly.network/docs/build-on-omnichain/restful-api/private/get-orders https://orderly.network/docs/build-on-omnichain/restful-api/private/get-algo-orders :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 boolean [params.trigger]: whether the order is a stop/algo order :param boolean [params.is_triggered]: whether the order has been triggered(False by default) :param str [params.side]: 'buy' or 'sell' :param boolean [params.paginate]: set to True if you want to fetch orders with pagination :param int params['until']: timestamp in ms of the latest order to fetch :returns Order[]: a list of `order structures ` """ if self.markets is None: await self.load_markets() isTrigger = self.safe_bool_2(params, 'stop', 'trigger', False) maxLimit = 100 if (isTrigger) else 500 paginate, paramsPaginate = self.handle_option_bool_and_params(params, 'fetchOrders', 'paginate', False) if paginate: return await self.fetch_paginated_call_incremental('fetchOrders', symbol, since, limit, paramsPaginate, 'page', maxLimit) request = {} market = None paramsOmitted = self.omit(paramsPaginate, ['stop', 'trigger']) if symbol is not None: market = self.market(symbol) request['symbol'] = market['id'] if since is not None: request['start_t'] = since if limit is not None: request['size'] = limit else: request['size'] = maxLimit if isTrigger: request['algo_type'] = 'STOP' requestUntil, paramsUntil = self.handle_until_option('end_t', request, paramsOmitted) response = None if isTrigger: response = await self.v1PrivateGetAlgoOrders(self.extend(requestUntil, paramsUntil)) else: response = await self.v1PrivateGetOrders(self.extend(requestUntil, paramsUntil)) # # { # "success": true, # "timestamp": 1702989203988, # "data": { # "meta": { # "total": 9, # "records_per_page": 25, # "current_page": 1 # }, # "rows": [{ # "order_id": 78151, # "user_id": 12345, # "price": 0.67772, # "type": "LIMIT", # "quantity": 20, # "amount": 10, # "executed_quantity": 20, # "total_executed_quantity": 20, # "visible_quantity": 1, # "symbol": "PERP_WOO_USDC", # "side": "BUY", # "status": "FILLED", # "total_fee": 0.5, # "fee_asset": "WOO", # "client_order_id": 1, # "average_executed_price": 0.67772, # "created_time": 1653563963000, # "updated_time": 1653564213000, # "realized_pnl": 123 # }] # } # } # data = self.safe_dict(response, 'data', response) orders = self.safe_list(data, 'rows') return self.parse_orders(orders, market, since, limit) async def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Order]: """ fetches information on multiple orders made by the user https://orderly.network/docs/build-on-omnichain/restful-api/private/get-orders https://orderly.network/docs/build-on-omnichain/restful-api/private/get-algo-orders :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 boolean [params.trigger]: whether the order is a stop/algo order :param boolean [params.is_triggered]: whether the order has been triggered(False by default) :param str [params.side]: 'buy' or 'sell' :param int params['until']: timestamp in ms of the latest order to fetch :param boolean [params.paginate]: set to True if you want to fetch orders with pagination :returns Order[]: a list of `order structures ` """ if self.markets is None: await self.load_markets() extendedParams = self.extend(params, {'status': 'INCOMPLETE'}) return await self.fetch_orders(symbol, since, limit, extendedParams) async def fetch_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Order]: """ fetches information on multiple orders made by the user https://orderly.network/docs/build-on-omnichain/restful-api/private/get-orders https://orderly.network/docs/build-on-omnichain/restful-api/private/get-algo-orders :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 boolean [params.trigger]: whether the order is a stop/algo order :param boolean [params.is_triggered]: whether the order has been triggered(False by default) :param str [params.side]: 'buy' or 'sell' :param int params['until']: timestamp in ms of the latest order to fetch :param boolean [params.paginate]: set to True if you want to fetch orders with pagination :returns Order[]: a list of `order structures ` """ if self.markets is None: await self.load_markets() extendedParams = self.extend(params, {'status': 'COMPLETED'}) return await self.fetch_orders(symbol, since, limit, extendedParams) async def fetch_order_trades(self, id: str, symbol: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Trade]: """ fetch all the trades made from a single order https://orderly.network/docs/build-on-omnichain/restful-api/private/get-all-trades-of-specific-order :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 ` """ if self.markets is None: await self.load_markets() market = None if symbol is not None: market = self.market(symbol) request = { 'oid': id, } response = await self.v1PrivateGetOrderOidTrades(self.extend(request, params)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "rows": [{ # "id": 2, # "symbol": "PERP_BTC_USDC", # "fee": 0.0001, # "fee_asset": "USDC", # "side": "BUY", # "order_id": 1, # "executed_price": 123, # "executed_quantity": 0.05, # "executed_timestamp": 1567382401000, # "is_maker": 1, # "realized_pnl": 123 # }] # } # } # data = self.safe_dict(response, 'data', {}) trades = self.safe_list(data, 'rows', []) return self.parse_trades(trades, market, since, limit, params) async def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Trade]: """ https://orderly.network/docs/build-on-omnichain/restful-api/private/get-trades fetch all trades made by the user :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 boolean [params.paginate]: set to True if you want to fetch trades with pagination :param int params['until']: timestamp in ms of the latest trade to fetch :returns Trade[]: a list of `trade structures ` """ if self.markets is None: await self.load_markets() paginate, paramsPaginate = self.handle_option_bool_and_params(params, 'fetchMyTrades', 'paginate', False) if paginate: return await self.fetch_paginated_call_incremental('fetchMyTrades', symbol, since, limit, paramsPaginate, 'page', 500) request = {} market = None if symbol is not None: market = self.market(symbol) request['symbol'] = market['id'] if since is not None: request['start_t'] = since if limit is not None: request['size'] = limit else: request['size'] = 500 requestUntil, paramsUntil = self.handle_until_option('end_t', request, paramsPaginate) response = await self.v1PrivateGetTrades(self.extend(requestUntil, paramsUntil)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "meta": { # "total": 9, # "records_per_page": 25, # "current_page": 1 # }, # "rows": [{ # "id": 2, # "symbol": "PERP_BTC_USDC", # "fee": 0.0001, # "fee_asset": "USDC", # "side": "BUY", # "order_id": 1, # "executed_price": 123, # "executed_quantity": 0.05, # "executed_timestamp": 1567382401000, # "is_maker": 1, # "realized_pnl": 123 # }] # } # } # data = self.safe_dict(response, 'data', {}) trades = self.safe_list(data, 'rows', []) return self.parse_trades(trades, market, since, limit, paramsUntil) def parse_balance(self, response: dict) -> Balances: result = { 'info': response, } balances = self.safe_list(response, 'holding', []) for i in range(0, len(balances)): balance = self.safe_dict(balances, i) code = self.safe_currency_code(self.safe_string(balance, 'token')) account = self.account() account['total'] = self.safe_string(balance, 'holding') account['used'] = self.safe_string(balance, 'frozen') if code is not None: result[code] = account return self.safe_balance(result) async def fetch_balance(self, params: dict = {}) -> Balances: """ query for balance and get the amount of funds available for trading or funds locked in orders https://orderly.network/docs/build-on-omnichain/restful-api/private/get-current-holding :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `balance structure ` """ if self.markets is None: await self.load_markets() response = await self.v1PrivateGetClientHolding(params) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "holding": [{ # "updated_time": 1580794149000, # "token": "BTC", # "holding": -28.000752, # "frozen": 123, # "pending_short": -2000 # }] # } # } # data = self.safe_dict(response, 'data', {}) return self.parse_balance(data) async def get_asset_history_rows(self, code: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[dict]: if self.markets is None: await self.load_markets() request = {} currency = None if code is not None: currency = self.currency(code) request['balance_token'] = self.safe_string(currency, 'id') if since is not None: request['start_t'] = since if limit is not None: request['pageSize'] = limit transactionType = self.safe_string(params, 'type') paramsOmitted = self.omit(params, 'type') if transactionType is not None: request['type'] = transactionType response = await self.v1PrivateGetAssetHistory(self.extend(request, paramsOmitted)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "meta": { # "total": 9, # "records_per_page": 25, # "current_page": 1 # }, # "rows": [{ # "id": "230707030600002", # "tx_id": "0x4b0714c63cc7abae72bf68e84e25860b88ca651b7d27dad1e32bf4c027fa5326", # "side": "WITHDRAW", # "token": "USDC", # "amount": 555, # "fee": 123, # "trans_status": "FAILED", # "created_time": 1688699193034, # "updated_time": 1688699193096, # "chain_id": "986532" # }] # } # } # data = self.safe_dict(response, 'data', {}) rows = self.safe_list(data, 'rows', []) return rows def parse_ledger_entry(self, item: dict, currency: Currency = None) -> LedgerEntry: currencyId = self.safe_string(item, 'token') code = self.safe_currency_code(currencyId, currency) currencyResolved = self.safe_currency(currencyId, currency) amount = self.safe_number(item, 'amount') side = self.safe_string(item, 'token_side') direction = 'in' if (side == 'DEPOSIT') else 'out' timestamp = self.safe_integer(item, 'created_time') fee = self.parse_token_and_fee_temp(item, 'fee_token', 'fee_amount') return self.safe_ledger_entry({ 'id': self.safe_string(item, 'id'), 'currency': code, 'account': self.safe_string(item, 'account'), 'referenceAccount': None, 'referenceId': self.safe_string(item, 'tx_id'), 'status': self.parse_transaction_status(self.safe_string(item, 'status')), 'amount': amount, 'before': None, 'after': None, 'fee': fee, 'direction': direction, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'type': self.parse_ledger_entry_type(self.safe_string(item, 'type')), 'info': item, }, currencyResolved) def parse_ledger_entry_type(self, type: Str) -> Str: types = { 'BALANCE': 'transaction', # Funds moved in/out wallet 'COLLATERAL': 'transfer', # Funds moved between portfolios } return self.safe_string(types, type, type) async def fetch_ledger(self, code: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[LedgerEntry]: """ fetch the history of changes, actions done by the user or operations that altered the balance of the user https://orderly.network/docs/build-on-omnichain/restful-api/private/get-asset-history :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 :returns dict: a `ledger structure ` """ rows = await self.get_asset_history_rows(code, since, limit, params) currency = None if code is not None: currency = self.currency(code) return self.parse_ledger(rows, currency, since, limit, params) def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction: # example in fetchLedger code = self.safe_string(transaction, 'token') movementDirection = self.safe_string_lower(transaction, 'token_side') if movementDirection == 'withdraw': movementDirection = 'withdrawal' fee = self.parse_token_and_fee_temp(transaction, 'fee_token', 'fee_amount') addressTo = self.safe_string(transaction, 'target_address') addressFrom = self.safe_string(transaction, 'source_address') timestamp = self.safe_integer(transaction, 'created_time') return { 'info': transaction, 'id': self.safe_string_2(transaction, 'id', 'withdraw_id'), 'txid': self.safe_string(transaction, 'tx_id'), 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'address': None, 'addressFrom': addressFrom, 'addressTo': addressTo, 'tag': self.safe_string(transaction, 'extra'), 'tagFrom': None, 'tagTo': None, 'type': movementDirection, 'amount': self.safe_number(transaction, 'amount'), 'currency': code, 'status': self.parse_transaction_status(self.safe_string(transaction, 'status')), 'updated': self.safe_integer(transaction, 'updated_time'), 'comment': None, 'internal': None, 'fee': fee, 'network': None, } def parse_transaction_status(self, status: Str) -> Str: statuses = { 'NEW': 'pending', 'CONFIRMING': 'pending', 'PROCESSING': 'pending', 'COMPLETED': 'ok', 'CANCELED': 'canceled', } return self.safe_string(statuses, status, status) async def fetch_deposits(self, code: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Transaction]: """ fetch all deposits made to an account https://orderly.network/docs/build-on-omnichain/restful-api/private/get-asset-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 :returns dict[]: a list of `transaction structures ` """ request = { 'side': 'DEPOSIT', } return await self.fetch_deposits_withdrawals(code, since, limit, self.extend(request, params)) async def fetch_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Transaction]: """ fetch all withdrawals made from an account https://orderly.network/docs/build-on-omnichain/restful-api/private/get-asset-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 :returns dict[]: a list of `transaction structures ` """ request = { 'side': 'WITHDRAW', } return await self.fetch_deposits_withdrawals(code, since, limit, self.extend(request, params)) async def fetch_deposits_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Transaction]: """ fetch history of deposits and withdrawals https://orderly.network/docs/build-on-omnichain/restful-api/private/get-asset-history :param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None :param int [limit]: max number of deposit/withdrawals to return, default is None :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a list of `transaction structure ` """ request = {} rows = await self.get_asset_history_rows(code, since, limit, self.extend(request, params)) currency = None if code is not None: currency = self.currency(code) # # { # "rows":[], # "meta":{ # "total":0, # "records_per_page":25, # "current_page":1 # }, # "success":true # } # return self.parse_transactions(rows, currency, since, limit, params) async def get_withdraw_nonce(self, params: dict = {}) -> Num: response = await self.v1PrivateGetWithdrawNonce(params) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "withdraw_nonce": 1 # } # } # data = self.safe_dict(response, 'data', {}) return self.safe_number(data, 'withdraw_nonce') def hash_message(self, message: object) -> str: hashed = self.hash(message, 'keccak', 'hex') return '0x' + hashed def sign_hash(self, hash: str, privateKey: str) -> str: signature = self.ecdsa(hash[-64:], privateKey[-64:], 'secp256k1', None) r = self.safe_string(signature, 'r', '') s = self.safe_string(signature, 's', '') v = self.int_to_base16(self.sum(27, signature['v'])) return '0x' + r.rjust(64, '0') + s.rjust(64, '0') + v def sign_message(self, message: object, privateKey: str) -> str: return self.sign_hash(self.hash_message(message), privateKey[-64:]) async def withdraw(self, code: str, amount: float, address: str, params: dict = {}) -> Transaction: """ make a withdrawal https://orderly.network/docs/build-on-omnichain/restful-api/private/create-withdraw-request :param str code: unified currency code :param float amount: the amount to withdraw :param str address: the address to withdraw to :param dict [params]: extra parameters specific to the exchange API endpoint :param str [params.tag]: memo / destination tag, required for currencies in options['withdrawTagRequiredCurrencies'] :returns dict: a `transaction structure ` """ if self.markets is None: await self.load_markets() self.check_address(address) codeUpper = code.upper() if codeUpper != 'USDC': raise NotSupported(self.id + ' withdraw() only support USDC') currency = self.currency(codeUpper) verifyingContractAddress = self.safe_string(self.options, 'verifyingContractAddress') chainId = self.safe_string(params, 'chainId') currencyNetworks = self.safe_dict(currency, 'networks', {}) coinNetwork = self.safe_dict(currencyNetworks, chainId, {}) coinNetworkId = self.safe_number(coinNetwork, 'id') if coinNetworkId is None: raise BadRequest(self.id + ' withdraw() require chainId parameter') withdrawNonce = await self.get_withdraw_nonce(params) nonce = self.nonce() domain = { 'chainId': chainId, 'name': 'Orderly', 'verifyingContract': verifyingContractAddress, 'version': '1', } messageTypes = { 'Withdraw': [ {'name': 'brokerId', 'type': 'string'}, {'name': 'chainId', 'type': 'uint256'}, {'name': 'receiver', 'type': 'address'}, {'name': 'token', 'type': 'string'}, {'name': 'amount', 'type': 'uint256'}, {'name': 'withdrawNonce', 'type': 'uint64'}, {'name': 'timestamp', 'type': 'uint64'}, ], } withdrawRequest = { 'brokerId': self.safe_string(self.options, 'keyBrokerId', 'woofi_pro'), 'chainId': self.parse_to_int(chainId), 'receiver': address, 'token': codeUpper, 'amount': self.number_to_string(amount), 'withdrawNonce': withdrawNonce, 'timestamp': nonce, } msg = self.eth_encode_structured_data(domain, messageTypes, withdrawRequest) signature = self.sign_message(msg, self.privateKey) request = { 'signature': signature, 'userAddress': address, 'verifyingContract': verifyingContractAddress, 'message': withdrawRequest, } paramsOmitted = self.omit(params, 'chainId') response = await self.v1PrivatePostWithdrawRequest(self.extend(request, paramsOmitted)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "withdraw_id": 123 # } # } # data = self.safe_dict(response, 'data', {}) return self.parse_transaction(data, currency) def parse_margin_mode(self, marginMode: dict, market: Market = None) -> MarginMode: # # { # "symbol": "PERP_BTC_USDC", # "default_margin_mode": "CROSS" # } # marketId = self.safe_string(marginMode, 'symbol') marketResolved = self.safe_market(marketId, market) return { 'info': marginMode, 'symbol': marketResolved['symbol'], 'marginMode': self.safe_string_lower(marginMode, 'default_margin_mode'), } async def fetch_margin_modes(self, symbols: Strings = None, params: dict = {}) -> MarginModes: """ fetches the set margin mode of every contract market https://orderly.network/docs/build-on-omnichain/restful-api/private/get-margin-modes :param str[] [symbols]: a list of unified market symbols :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a list of `margin mode structures ` """ if self.markets is None: await self.load_markets() symbolsNormalized = self.market_symbols(symbols) response = await self.v1PrivateGetClientMarginModes(params) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "rows": [{ # "symbol": "PERP_BTC_USDC", # "default_margin_mode": "CROSS" # }] # } # } # data = self.safe_dict(response, 'data', {}) rows = self.safe_list(data, 'rows', []) return self.parse_margin_modes(rows, symbolsNormalized, 'symbol') async def fetch_margin_mode(self, symbol: str, params: dict = {}) -> MarginMode: """ fetches the set margin mode of a contract market https://orderly.network/docs/build-on-omnichain/restful-api/private/get-margin-modes :param str symbol: unified symbol of the market :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `margin mode structure ` """ if self.markets is None: await self.load_markets() market = self.market(symbol) marginModes = await self.fetch_margin_modes([market['symbol']], params) marginMode = self.safe_dict(marginModes, market['symbol']) if marginMode is None: raise BadSymbol(self.id + ' fetchMarginMode() did not return a margin mode for ' + market['symbol']) return marginMode async def set_margin_mode(self, marginMode: str, symbol: Str = None, params: dict = {}): """ set margin mode to 'cross' or 'isolated' for a market https://orderly.network/docs/build-on-omnichain/restful-api/private/update-margin-mode :param str marginMode: 'cross' or 'isolated' :param str symbol: unified market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: response from the exchange """ if symbol is None: raise ArgumentsRequired(self.id + ' setMarginMode() requires a symbol argument') if self.markets is None: await self.load_markets() marginModeValue = marginMode.lower() if marginModeValue != 'cross' and marginModeValue != 'isolated': raise BadRequest(self.id + ' setMarginMode() marginMode must be either cross or isolated') market = self.market(symbol) request = { 'symbol': market['id'], 'default_margin_mode': marginModeValue.upper(), } # # { # "success": true, # "timestamp": 1702989203989 # } # return await self.v1PrivatePostClientMarginMode(self.extend(request, params)) def parse_margin_modification(self, data: dict, market: Market = None) -> MarginModification: # # { # "success": true, # "timestamp": 1702989203989 # } # timestamp = self.safe_integer(data, 'timestamp') success = self.safe_bool(data, 'success', False) return { 'info': data, 'symbol': self.safe_string(market, 'symbol'), 'type': None, 'marginMode': 'isolated', 'amount': None, 'total': None, 'code': self.safe_string(market, 'settle'), 'status': 'ok' if (success) else 'failed', 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), } async def modify_margin_helper(self, symbol: str, amount: float, type: str, params: dict = {}) -> MarginModification: """ @ignore add or reduce isolated position margin https://orderly.network/docs/build-on-omnichain/restful-api/private/add-or-reduce-position-margin :param str symbol: unified market symbol :param float amount: amount of margin to add or reduce :param str type: 'ADD' or 'REDUCE' :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `margin structure ` """ if self.markets is None: await self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], 'amount': self.number_to_string(amount), 'type': type, } response = await self.v1PrivatePostPositionMargin(self.extend(request, params)) # # { # "success": true, # "timestamp": 1702989203989 # } # modification = self.parse_margin_modification(response, market) modification['type'] = 'add' if (type == 'ADD') else 'reduce' modification['amount'] = self.parse_number(self.number_to_string(amount)) return modification async def add_margin(self, symbol: str, amount: float, params: dict = {}) -> MarginModification: """ add margin to an isolated position https://orderly.network/docs/build-on-omnichain/restful-api/private/add-or-reduce-position-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 ` """ return await self.modify_margin_helper(symbol, amount, 'ADD', params) async def reduce_margin(self, symbol: str, amount: float, params: dict = {}) -> MarginModification: """ remove margin from an isolated position https://orderly.network/docs/build-on-omnichain/restful-api/private/add-or-reduce-position-margin :param str symbol: unified market symbol :param float amount: amount of margin to remove :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `margin structure ` """ return await self.modify_margin_helper(symbol, amount, 'REDUCE', params) def parse_leverage(self, leverage: dict, market: Market = None) -> Leverage: leverageValue = self.safe_integer(leverage, 'max_leverage') return { 'info': leverage, 'symbol': self.safe_string(market, 'symbol'), 'marginMode': None, 'longLeverage': leverageValue, 'shortLeverage': leverageValue, } async def fetch_leverage(self, symbol: str, params: dict = {}) -> Leverage: """ fetch the set leverage for a market https://orderly.network/docs/build-on-omnichain/restful-api/private/get-account-information :param str symbol: unified market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `leverage structure ` """ if self.markets is None: await self.load_markets() market = self.market(symbol) response = await self.v1PrivateGetClientInfo(params) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "account_id": "", # "email": "test@test.com", # "account_mode": "FUTURES", # "max_leverage": 20, # "taker_fee_rate": 123, # "maker_fee_rate": 123, # "futures_taker_fee_rate": 123, # "futures_maker_fee_rate": 123, # "maintenance_cancel_orders": true, # "imr_factor": { # "PERP_BTC_USDC": 123, # "PERP_ETH_USDC": 123, # "PERP_NEAR_USDC": 123 # }, # "max_notional": { # "PERP_BTC_USDC": 123, # "PERP_ETH_USDC": 123, # "PERP_NEAR_USDC": 123 # } # } # } # data = self.safe_dict(response, 'data', {}) return self.parse_leverage(data, market) async def set_leverage(self, leverage: int, symbol: Str = None, params: dict = {}): """ set the level of leverage for a market https://orderly.network/docs/build-on-omnichain/restful-api/private/update-leverage-setting :param int [leverage]: the rate of leverage :param str [symbol]: unified market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: response from the exchange """ if self.markets is None: await self.load_markets() if (leverage < 1) or (leverage > 50): raise BadRequest(self.id + ' leverage should be between 1 and 50') request = { 'leverage': leverage, } return await self.v1PrivatePostClientLeverage(self.extend(request, params)) def parse_position(self, position: dict, market: Market = None) -> Position: # # { # "IMR_withdraw_orders": 0.1, # "MMR_with_orders": 0.05, # "average_open_price": 27908.14386047, # "cost_position": -139329.358492, # "est_liq_price": 117335.92899428, # "fee_24_h": 123, # "imr": 0.1, # "last_sum_unitary_funding": 70.38, # "mark_price": 27794.9, # "mmr": 0.05, # "pending_long_qty": 123, # "pending_short_qty": 123, # "pnl_24_h": 123, # "position_qty": -5, # "settle_price": 27865.8716984, # "symbol": "PERP_BTC_USDC", # "timestamp": 1685429350571, # "unsettled_pnl": 354.858492 # } # contract = self.safe_string(position, 'symbol') marketResolved = self.safe_market(contract, market) size = self.safe_string(position, 'position_qty') side = None if Precise.string_gt(size, '0'): side = 'long' else: side = 'short' contractSize = self.safe_string(marketResolved, 'contractSize') markPrice = self.safe_string(position, 'mark_price') timestamp = self.safe_integer(position, 'timestamp') entryPrice = self.safe_string(position, 'average_open_price') unrealisedPnl = self.safe_string(position, 'unsettled_pnl') size = Precise.string_abs(size) notional = Precise.string_mul(size, markPrice) return self.safe_position({ 'info': position, 'id': None, 'symbol': self.safe_string(marketResolved, 'symbol'), 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'lastUpdateTimestamp': None, 'initialMargin': None, 'initialMarginPercentage': None, 'maintenanceMargin': None, 'maintenanceMarginPercentage': None, 'entryPrice': self.parse_number(entryPrice), 'notional': self.parse_number(notional), 'leverage': None, 'unrealizedPnl': self.parse_number(unrealisedPnl), 'contracts': self.parse_number(size), 'contractSize': self.parse_number(contractSize), 'marginRatio': None, 'liquidationPrice': self.safe_number(position, 'est_liq_price'), 'markPrice': self.parse_number(markPrice), 'lastPrice': None, 'collateral': None, 'marginMode': 'cross', 'side': side, 'percentage': None, 'hedged': None, 'stopLossPrice': None, 'takeProfitPrice': None, }) async def fetch_position(self, symbol: str, params: dict = {}) -> Position: """ https://orderly.network/docs/build-on-omnichain/restful-api/private/get-one-position-info fetch data on an open position :param str symbol: unified market symbol of the market the position is held in :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `position structure ` """ if self.markets is None: await self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], } response = await self.v1PrivateGetPositionSymbol(self.extend(request, params)) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "IMR_withdraw_orders": 0.1, # "MMR_with_orders": 0.05, # "average_open_price": 27908.14386047, # "cost_position": -139329.358492, # "est_liq_price": 117335.92899428, # "fee_24_h": 123, # "imr": 0.1, # "last_sum_unitary_funding": 70.38, # "mark_price": 27794.9, # "mmr": 0.05, # "pending_long_qty": 123, # "pending_short_qty": 123, # "pnl_24_h": 123, # "position_qty": -5, # "settle_price": 27865.8716984, # "symbol": "PERP_BTC_USDC", # "timestamp": 1685429350571, # "unsettled_pnl": 354.858492 # } # } # data = self.safe_dict(response, 'data', {}) return self.parse_position(data, market) async def fetch_positions(self, symbols: Strings = None, params: dict = {}) -> list[Position]: """ fetch all open positions https://orderly.network/docs/build-on-omnichain/restful-api/private/get-all-positions-info :param str[] [symbols]: list of unified market symbols :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict[]: a list of `position structure ` """ if self.markets is None: await self.load_markets() response = await self.v1PrivateGetPositions(params) # # { # "success": true, # "timestamp": 1702989203989, # "data": { # "current_margin_ratio_with_orders": 1.2385, # "free_collateral": 450315.09115, # "initial_margin_ratio": 0.1, # "initial_margin_ratio_with_orders": 0.1, # "maintenance_margin_ratio": 0.05, # "maintenance_margin_ratio_with_orders": 0.05, # "margin_ratio": 1.2385, # "open_margin_ratio": 1.2102, # "total_collateral_value": 489865.71329, # "total_pnl_24_h": 123, # "rows": [{ # "IMR_withdraw_orders": 0.1, # "MMR_with_orders": 0.05, # "average_open_price": 27908.14386047, # "cost_position": -139329.358492, # "est_liq_price": 117335.92899428, # "fee_24_h": 123, # "imr": 0.1, # "last_sum_unitary_funding": 70.38, # "mark_price": 27794.9, # "mmr": 0.05, # "pending_long_qty": 123, # "pending_short_qty": 123, # "pnl_24_h": 123, # "position_qty": -5, # "settle_price": 27865.8716984, # "symbol": "PERP_BTC_USDC", # "timestamp": 1685429350571, # "unsettled_pnl": 354.858492 # }] # } # } # result = self.safe_dict(response, 'data', {}) positions = self.safe_list(result, 'rows', []) return self.parse_positions(positions, symbols) def nonce(self) -> int: return self.milliseconds() def sign(self, path: str, section: list[str] = ['public'], method: str = 'GET', params: dict = {}) -> dict: version = section[0] access = section[1] pathWithParams = self.implode_params(path, params) apiUrl = self.safe_string(self.urls['api'], access) if apiUrl is None: raise ExchangeError(self.id + ' sign() has no API URL for self endpoint') url = apiUrl + '/' + version + '/' requestParams = self.keysort(self.omit(params, self.extract_params(path))) requestBody = None requestHeaders = None if access == 'public': url += pathWithParams if len(requestParams) > 0: url += '?' + self.urlencode(requestParams) else: self.check_required_credentials() if (method == 'POST' or method == 'PUT') and (path == 'algo/order' or path == 'order' or path == 'batch-order'): isSandboxMode = self.safe_bool(self.options, 'sandboxMode', False) if not isSandboxMode: brokerId = self.safe_string(self.options, 'brokerId', 'CCXT') if path == 'batch-order': ordersList = self.safe_list(requestParams, 'orders', []) for i in range(0, len(ordersList)): requestParams['orders'][i]['order_tag'] = brokerId else: requestParams['order_tag'] = brokerId requestParams = self.keysort(requestParams) auth = '' ts = str(self.nonce()) url += pathWithParams hasKeyPrefix = self.apiKey.find('ed25519:') >= 0 apiKey = self.apiKey if (hasKeyPrefix) else ('ed25519:' + self.apiKey) authHeaders = { 'orderly-account-id': self.accountId, 'orderly-key': apiKey, 'orderly-timestamp': ts, } auth = ts + method + '/' + version + '/' + pathWithParams if method == 'POST' or method == 'PUT': requestBody = self.json(requestParams) auth += requestBody authHeaders['content-type'] = 'application/json' else: if len(requestParams) > 0: url += '?' + self.urlencode(requestParams) auth += '?' + self.rawencode(requestParams) authHeaders['content-type'] = 'application/x-www-form-urlencoded' if method == 'DELETE': requestBody = '' secret = self.secret if self.secret.find('ed25519:') >= 0: parts = self.secret.split('ed25519:') secret = parts[1] signature = self.eddsa(self.encode(auth), self.base58_to_binary(secret), 'ed25519') authHeaders['orderly-signature'] = self.urlencode_base64(self.base64_to_binary(signature)) requestHeaders = authHeaders return {'url': url, 'method': method, 'body': requestBody, 'headers': requestHeaders} def handle_errors(self, code: int, reason: str, url: str, method: str, headers: dict, body: str, response: object, requestHeaders: dict, requestBody: Str): if response is None: return None # fallback to default error handler # # 400 Bad Request {"success":false,"code":-1012,"message":"Amount is required for buy market orders when margin disabled."} # {"code":"-1011","message":"The system is under maintenance.","success":false} # success = self.safe_bool(response, 'success', False) errorCode = self.safe_string(response, 'code') if not success: feedback = self.id + ' ' + self.json(response) self.throw_broadly_matched_exception(self.exceptions['broad'], body, feedback) self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback) raise ExchangeError(feedback) return None