Files
ccxt_with_mt5/ccxt/async_support/modetrade.py
lz_db 0fab423a18 add
2025-11-16 12:31:03 +08:00

2819 lines
123 KiB
Python

# -*- 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.modetrade import ImplicitAPI
from ccxt.base.types import Any, Balances, Currencies, Currency, Int, LedgerEntry, Leverage, Market, Num, Order, OrderBook, OrderRequest, OrderSide, OrderType, Position, Str, Strings, FundingRate, FundingRates, Trade, TradingFees, Transaction
from typing import List
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 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 modetrade(Exchange, ImplicitAPI):
def describe(self) -> Any:
return self.deep_extend(super(modetrade, self).describe(), {
'id': 'modetrade',
'name': 'Mode Trade',
'countries': ['KY'], # Cayman Islands
'rateLimit': 100,
'version': 'v1',
'certified': False,
'pro': True,
'dex': True,
'hostname': 'trade.mode.network',
'has': {
'CORS': None,
'spot': False,
'margin': False,
'swap': True,
'future': False,
'option': False,
'addMargin': False,
'cancelAllOrders': True,
'cancelOrder': True,
'cancelOrders': True,
'cancelWithdraw': False,
'closeAllPositions': False,
'closePosition': False,
'createConvertTrade': False,
'createDepositAddress': False,
'createMarketBuyOrderWithCost': False,
'createMarketOrder': True,
'createMarketOrderWithCost': False,
'createMarketSellOrderWithCost': False,
'createOrder': True,
'createOrderWithTakeProfitAndStopLoss': True,
'createReduceOnlyOrder': True,
'createStopLimitOrder': True,
'createStopLossOrder': True,
'createStopMarketOrder': True,
'createStopOrder': True,
'createTakeProfitOrder': True,
'createTrailingAmountOrder': False,
'createTrailingPercentOrder': False,
'createTriggerOrder': True,
'fetchAccounts': False,
'fetchBalance': True,
'fetchCanceledOrders': False,
'fetchClosedOrder': False,
'fetchClosedOrders': True,
'fetchConvertCurrencies': False,
'fetchConvertQuote': False,
'fetchCurrencies': True,
'fetchDepositAddress': False,
'fetchDeposits': True,
'fetchDepositsWithdrawals': True,
'fetchFundingHistory': True,
'fetchFundingInterval': True,
'fetchFundingIntervals': False,
'fetchFundingRate': True,
'fetchFundingRateHistory': True,
'fetchFundingRates': True,
'fetchIndexOHLCV': False,
'fetchLedger': True,
'fetchLeverage': True,
'fetchMarginAdjustmentHistory': False,
'fetchMarginMode': False,
'fetchMarkets': True,
'fetchMarkOHLCV': False,
'fetchMyTrades': True,
'fetchOHLCV': True,
'fetchOpenInterestHistory': False,
'fetchOpenOrder': False,
'fetchOpenOrders': True,
'fetchOrder': True,
'fetchOrderBook': True,
'fetchOrders': True,
'fetchOrderTrades': True,
'fetchPosition': True,
'fetchPositionMode': False,
'fetchPositions': True,
'fetchPremiumIndexOHLCV': False,
'fetchStatus': True,
'fetchTicker': False,
'fetchTickers': False,
'fetchTime': True,
'fetchTrades': True,
'fetchTradingFee': False,
'fetchTradingFees': True,
'fetchTransactions': 'emulated',
'fetchTransfers': False,
'fetchWithdrawals': True,
'reduceMargin': False,
'setLeverage': True,
'setMargin': False,
'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/cec2b7f1-3b2b-4502-971b-447ee1937d6b',
'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://trade.mode.network',
'referral': {
'url': 'https://trade.mode.network?ref=MODETRADE',
'discount': 0.2,
},
},
'api': {
'v1': {
'public': {
'get': {
'public/volume/stats': 1,
'public/broker/name': 1,
'public/chain_info/{broker_id}': 1,
'public/system_info': 1,
'public/vault_balance': 1,
'public/insurancefund': 1,
'public/chain_info': 1,
'faucet/usdc': 1,
'public/account': 1,
'get_account': 1,
'registration_nonce': 1,
'get_orderly_key': 1,
'public/liquidation': 1,
'public/liquidated_positions': 1,
'public/config': 1,
'public/campaign/ranking': 10,
'public/campaign/stats': 10,
'public/campaign/user': 10,
'public/campaign/stats/details': 10,
'public/campaigns': 10,
'public/points/leaderboard': 1,
'client/points': 1,
'public/points/epoch': 1,
'public/points/epoch_dates': 1,
'public/referral/check_ref_code': 1,
'public/referral/verify_ref_code': 1,
'referral/admin_info': 1,
'referral/info': 1,
'referral/referee_info': 1,
'referral/referee_rebate_summary': 1,
'referral/referee_history': 1,
'referral/referral_history': 1,
'referral/rebate_summary': 1,
'client/distribution_history': 1,
'tv/config': 1,
'tv/history': 1,
'tv/symbol_info': 1,
'public/funding_rate_history': 1,
'public/funding_rate/{symbol}': 0.33,
'public/funding_rates': 1,
'public/info': 1,
'public/info/{symbol}': 1,
'public/market_trades': 1,
'public/token': 1,
'public/futures': 1,
'public/futures/{symbol}': 1,
},
'post': {
'register_account': 1,
},
},
'private': {
'get': {
'client/key_info': 6,
'client/orderly_key_ip_restriction': 6,
'order/{oid}': 1,
'client/order/{client_order_id}': 1,
'algo/order/{oid}': 1,
'algo/client/order/{client_order_id}': 1,
'orders': 1,
'algo/orders': 1,
'trade/{tid}': 1,
'trades': 1,
'order/{oid}/trades': 1,
'client/liquidator_liquidations': 1,
'liquidations': 1,
'asset/history': 60,
'client/holding': 1,
'withdraw_nonce': 1,
'settle_nonce': 1,
'pnl_settlement/history': 1,
'volume/user/daily': 60,
'volume/user/stats': 60,
'client/statistics': 60,
'client/info': 60,
'client/statistics/daily': 60,
'positions': 3.33,
'position/{symbol}': 3.33,
'funding_fee/history': 30,
'notification/inbox/notifications': 60,
'notification/inbox/unread': 60,
'volume/broker/daily': 60,
'broker/fee_rate/default': 10,
'broker/user_info': 10,
'orderbook/{symbol}': 1,
'kline': 1,
},
'post': {
'orderly_key': 1,
'client/set_orderly_key_ip_restriction': 6,
'client/reset_orderly_key_ip_restriction': 6,
'order': 1,
'batch-order': 10,
'algo/order': 1,
'liquidation': 1,
'claim_insurance_fund': 1,
'withdraw_request': 1,
'settle_pnl': 1,
'notification/inbox/mark_read': 60,
'notification/inbox/mark_read_all': 60,
'client/leverage': 120,
'client/maintenance_config': 60,
'delegate_signer': 10,
'delegate_orderly_key': 10,
'delegate_settle_pnl': 10,
'delegate_withdraw_request': 10,
'broker/fee_rate/set': 10,
'broker/fee_rate/set_default': 10,
'broker/fee_rate/default': 10,
'referral/create': 10,
'referral/update': 10,
'referral/bind': 10,
'referral/edit_split': 10,
},
'put': {
'order': 1,
'algo/order': 1,
},
'delete': {
'order': 1,
'algo/order': 1,
'client/order': 1,
'algo/client/order': 1,
'algo/orders': 1,
'orders': 1,
'batch-order': 1,
'client/batch-order': 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': 'CCXTMODE',
'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 self 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(modetrade, self).set_sandbox_mode(enable)
self.options['sandboxMode'] = enable
async def fetch_status(self, params={}):
"""
the latest known information on the availability of the exchange API
https://orderly.network/docs/build-on-evm/evm-api/restful-api/public/get-system-maintenance-status
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
"""
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={}) -> Int:
"""
fetches the current integer timestamp in milliseconds from the exchange server
https://orderly.network/docs/build-on-evm/evm-api/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')
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)
settleId: Str = self.safe_string(parts, 2)
settle: Str = self.safe_currency_code(settleId)
symbol = base + '/' + quote + ':' + settle
return {
'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={}) -> List[Market]:
"""
retrieves data on all markets for modetrade
https://orderly.network/docs/build-on-evm/evm-api/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={}) -> Currencies:
"""
fetches all available currencies on an exchange
https://orderly.network/docs/build-on-evm/evm-api/restful-api/public/get-token-info
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an associative dictionary of currencies
"""
result: dict = {}
response = await 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
# }]
# }
# ]
# }
# }
#
data = self.safe_dict(response, 'data', {})
tokenRows = self.safe_list(data, 'rows', [])
for i in range(0, len(tokenRows)):
token = tokenRows[i]
currencyId = self.safe_string(token, 'token')
networks = self.safe_list(token, 'chain_details')
code = self.safe_currency_code(currencyId)
minPrecision = None
resultingNetworks: dict = {}
for j in range(0, len(networks)):
network = networks[j]
# TODO: transform chain id to human readable name
networkId = self.safe_string(network, 'chain_id')
precision = self.parse_precision(self.safe_string(network, 'decimals'))
if precision is not None:
minPrecision = precision if (minPrecision is None) else Precise.string_min(precision, minPrecision)
resultingNetworks[networkId] = {
'id': networkId,
'network': networkId,
'limits': {
'withdraw': {
'min': None,
'max': None,
},
'deposit': {
'min': None,
'max': None,
},
},
'active': None,
'deposit': None,
'withdraw': None,
'fee': self.safe_number(network, 'withdrawal_fee'),
'precision': self.parse_number(precision),
'info': network,
}
result[code] = self.safe_currency_structure({
'id': currencyId,
'name': currencyId,
'code': code,
'precision': self.parse_number(minPrecision),
'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,
})
return result
def parse_token_and_fee_temp(self, item, feeTokenKey, feeAmountKey):
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": "PERP_ETH_USDC",
# "side": "SELL",
# "executed_price": 46222.35,
# "executed_quantity": 0.0012,
# "executed_timestamp": "1683878609166"
# }
#
# fetchOrderTrades, fetchOrder
#
# {
# "id": "99119876",
# "symbol": "PERP_BTC_USDC",
# "fee": "0.0024",
# "side": "BUY",
# "executed_timestamp": "1641481113084",
# "order_id": "87001234",
# "order_tag": "default", <-- self param only in "fetchOrderTrades"
# "executed_price": "1",
# "executed_quantity": "12",
# "fee_asset": "BTC",
# "is_maker": "1"
# }
#
isFromFetchOrder = ('id' in trade)
timestamp = self.safe_integer(trade, 'executed_timestamp')
marketId = self.safe_string(trade, 'symbol')
market = self.safe_market(marketId, market)
symbol = market['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')
feeCost = self.safe_string(fee, 'cost')
if feeCost is not None:
fee['cost'] = feeCost
cost = Precise.string_mul(price, amount)
side = self.safe_string_lower(trade, 'side')
id = self.safe_string(trade, 'id')
takerOrMaker: Str = 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': cost,
'order': order_id,
'takerOrMaker': takerOrMaker,
'type': None,
'fee': fee,
'info': trade,
}, market)
async def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
"""
get the list of most recent trades for a particular symbol
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=public-trades>`
"""
await self.load_markets()
market = self.market(symbol)
request: dict = {
'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, 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')
market = 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': market['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):
intervals: dict = {
'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={}) -> FundingRate:
"""
fetch the current funding rate interval
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=funding-rate-structure>`
"""
return await self.fetch_funding_rate(symbol, params)
async def fetch_funding_rate(self, symbol: str, params={}) -> FundingRate:
"""
fetch the current funding rate
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=funding-rate-structure>`
"""
await self.load_markets()
market = self.market(symbol)
request: dict = {
'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={}) -> FundingRates:
"""
fetch the current funding rate for multiple markets
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=funding-rate-structure>`
"""
await self.load_markets()
symbols = 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, symbols)
async def fetch_funding_rate_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
"""
fetches historical funding rate prices
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` 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 <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
"""
await self.load_markets()
paginate = False
paginate, params = self.handle_option_and_params(params, 'fetchFundingRateHistory', 'paginate')
if paginate:
return await self.fetch_paginated_call_incremental('fetchFundingRateHistory', symbol, since, limit, params, 'page', 25)
request: dict = {}
if symbol is not None:
market = self.market(symbol)
symbol = market['symbol']
request['symbol'] = market['id']
if since is not None:
request['start_t'] = since
request, params = self.handle_until_option('end_t', request, params, 0.001)
response = await self.v1PublicGetPublicFundingRateHistory(self.extend(request, params))
#
# {
# "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, symbol, since, limit)
def parse_income(self, income, market: Market = None):
#
# {
# "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={}):
"""
fetch the history of funding payments paid and received on self account
https://orderly.network/docs/build-on-omnichain/evm-api/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 <https://docs.ccxt.com/#/?id=funding-history-structure>`
"""
await self.load_markets()
paginate = False
paginate, params = self.handle_option_and_params(params, 'fetchFundingHistory', 'paginate')
if paginate:
return await self.fetch_paginated_call_incremental('fetchFundingHistory', symbol, since, limit, params, 'page', 500)
request: dict = {}
market: 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(params, 'until') # unified in milliseconds
params = self.omit(params, ['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, params))
#
# {
# "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={}) -> TradingFees:
"""
fetch the trading fees for multiple markets
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/get-account-information
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a dictionary of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>` indexed by market symbols
"""
await self.load_markets()
response = await self.v1PrivateGetClientInfo(params)
#
# {
# "success": True,
# "timestamp": 1702989203989,
# "data": {
# "account_id": "<string>",
# "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: dict = {}
for i in range(0, len(self.symbols)):
symbol = self.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={}) -> OrderBook:
"""
fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
https://orderly.network/docs/build-on-evm/evm-api/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: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
"""
await self.load_markets()
market = self.market(symbol)
request: dict = {
'symbol': market['id'],
}
if limit is not None:
limit = min(limit, 1000)
request['max_level'] = limit
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, 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={}) -> List[list]:
"""
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/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, open, high, low, close, volume
"""
await self.load_markets()
market = self.market(symbol)
request: dict = {
'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
# 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, self always returns 0 for limit order
marketId = self.safe_string(order, 'symbol')
market = self.safe_market(marketId, market)
symbol = market['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_value_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.omit_zero(self.safe_value_2(order, 'executed', 'totalExecutedQuantity'))
average = self.omit_zero(self.safe_string_2(order, 'average_executed_price', 'averageExecutedPrice'))
remaining = Precise.string_sub(cost, filled)
fee = self.safe_value_2(order, 'total_fee', 'totalFee')
feeCurrency = self.safe_string_2(order, 'fee_asset', 'feeAsset')
transactions = self.safe_value(order, 'Transactions')
triggerPrice = self.safe_number(order, 'triggerPrice')
takeProfitPrice: Num = None
stopLossPrice: Num = None
childOrders = self.safe_value(order, 'childOrders')
if childOrders is not None:
first = self.safe_value(childOrders, 0)
innerChildOrders = self.safe_value(first, 'childOrders', [])
innerChildOrdersLength = len(innerChildOrders)
if innerChildOrdersLength > 0:
takeProfitOrder = self.safe_value(innerChildOrders, 0)
stopLossOrder = self.safe_value(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': remaining, # TO_DO
'cost': cost,
'trades': transactions,
'fee': {
'cost': fee,
'currency': feeCurrency,
},
'info': order,
}, market)
def parse_time_in_force(self, timeInForce: Str):
timeInForces: dict = {
'ioc': 'IOC',
'fok': 'FOK',
'post_only': 'PO',
}
return self.safe_string(timeInForces, timeInForce, None)
def parse_order_status(self, status: Str):
if status is not None:
statuses: dict = {
'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 status
def parse_order_type(self, type: Str):
types: dict = {
'LIMIT': 'limit',
'MARKET': 'market',
'POST_ONLY': 'limit',
}
return self.safe_string_lower(types, type, type)
def create_order_request(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
"""
@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()
market = self.market(symbol)
orderSide = side.upper()
request: dict = {
'symbol': market['id'],
'side': orderSide,
}
triggerPrice = self.safe_string_2(params, 'triggerPrice', 'stopPrice')
stopLoss = self.safe_value(params, 'stopLoss')
takeProfit = self.safe_value(params, 'takeProfit')
algoType = self.safe_string(params, 'algoType')
isConditional = triggerPrice is not None or stopLoss is not None or takeProfit is not None or (self.safe_value(params, 'childOrders') 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:
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 (stopLoss is not None) or (takeProfit is not None):
request['algo_type'] = 'TP_SL'
outterOrder: dict = {
'symbol': market['id'],
'reduce_only': False,
'algo_type': 'POSITIONAL_TP_SL',
'child_orders': [],
}
childOrders = outterOrder['child_orders']
closeSide = 'SELL' if (orderSide == 'BUY') else 'BUY'
if stopLoss is not None:
stopLossPrice = self.safe_number_2(stopLoss, 'triggerPrice', 'price', stopLoss)
stopLossOrder: dict = {
'side': closeSide,
'algo_type': 'TP_SL',
'trigger_price': self.price_to_precision(symbol, stopLossPrice),
'type': 'LIMIT',
'reduce_only': True,
}
childOrders.append(stopLossOrder)
if takeProfit is not None:
takeProfitPrice = self.safe_number_2(takeProfit, 'triggerPrice', 'price', takeProfit)
takeProfitOrder: dict = {
'side': closeSide,
'algo_type': 'TP_SL',
'trigger_price': self.price_to_precision(symbol, takeProfitPrice),
'type': 'LIMIT',
'reduce_only': True,
}
outterOrder.append(takeProfitOrder)
request['child_orders'] = [outterOrder]
params = self.omit(params, ['reduceOnly', 'reduce_only', 'clOrdID', 'clientOrderId', 'client_order_id', 'postOnly', 'timeInForce', 'stopPrice', 'triggerPrice', 'stopLoss', 'takeProfit'])
return self.extend(request, params)
async def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
"""
create a trade order
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/create-order
https://orderly.network/docs/build-on-evm/evm-api/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 alternative for the amount
:param str [params.clientOrderId]: a unique id for the order
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
"""
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_value(params, 'stopLoss')
takeProfit = self.safe_value(params, 'takeProfit')
isConditional = triggerPrice is not None or stopLoss is not None or takeProfit is not None or (self.safe_value(params, 'childOrders') 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={}):
"""
*contract only* create a list of trade orders
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=order-structure>`
"""
await self.load_markets()
ordersRequests = []
for i in range(0, len(orders)):
rawOrder = 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_value(orderParams, 'stopLoss')
takeProfit = self.safe_value(orderParams, 'takeProfit')
isConditional = triggerPrice is not None or stopLoss is not None or takeProfit is not None or (self.safe_value(orderParams, 'childOrders') 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: dict = {
'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={}):
"""
edit a trade order
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/edit-order
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=order-structure>`
"""
await self.load_markets()
market = self.market(symbol)
request: dict = {
'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)
isConditional = (triggerPrice is not None) or (self.safe_value(params, 'childOrders') 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)
params = self.omit(params, ['stopPrice', 'triggerPrice', 'takeProfitPrice', 'stopLossPrice', 'trailingTriggerPrice', 'trailingAmount', 'trailingPercent'])
response = None
if isConditional:
response = await self.v1PrivatePutAlgoOrder(self.extend(request, params))
else:
request['symbol'] = market['id']
request['side'] = side.upper()
orderType = type.upper()
timeInForce = self.safe_string_lower(params, 'timeInForce')
isMarket = orderType == 'MARKET'
postOnly = self.is_post_only(isMarket, None, params)
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(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id', 'postOnly', 'timeInForce'])
if clientOrderId is not None:
request['client_order_id'] = clientOrderId
# request['side'] = side.upper()
# request['symbol'] = market['id']
response = await self.v1PrivatePutOrder(self.extend(request, params))
#
# {
# "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={}):
"""
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/cancel-order
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/cancel-order-by-client_order_id
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/cancel-algo-order
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=order-structure>`
"""
trigger = self.safe_bool_2(params, 'stop', 'trigger', False)
params = self.omit(params, ['stop', 'trigger'])
if not trigger and (symbol is None):
raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
await self.load_markets()
market: Market = None
if symbol is not None:
market = self.market(symbol)
request: dict = {
'symbol': market['id'],
}
clientOrderIdUnified = self.safe_string_2(params, 'clOrdID', 'clientOrderId')
clientOrderIdExchangeSpecific = self.safe_string(params, 'client_order_id', clientOrderIdUnified)
isByClientOrder = clientOrderIdExchangeSpecific is not None
response = None
if trigger:
if isByClientOrder:
request['client_order_id'] = clientOrderIdExchangeSpecific
params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
response = await self.v1PrivateDeleteAlgoClientOrder(self.extend(request, params))
else:
request['order_id'] = id
response = await self.v1PrivateDeleteAlgoOrder(self.extend(request, params))
else:
if isByClientOrder:
request['client_order_id'] = clientOrderIdExchangeSpecific
params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
response = await self.v1PrivateDeleteClientOrder(self.extend(request, params))
else:
request['order_id'] = id
response = await self.v1PrivateDeleteOrder(self.extend(request, params))
#
# {
# "success": True,
# "timestamp": 1702989203988,
# "data": {
# "status": "CANCEL_SENT"
# }
# }
#
# {
# "success": True,
# "timestamp": 1702989203988,
# "status": "CANCEL_SENT"
# }
#
extendParams: dict = {'symbol': symbol}
if isByClientOrder:
extendParams['client_order_id'] = clientOrderIdExchangeSpecific
else:
extendParams['id'] = id
if trigger:
return self.extend(self.parse_order(response), 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={}):
"""
cancel multiple orders
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/batch-cancel-orders
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=order-structure>`
"""
await self.load_markets()
clientOrderIds = self.safe_list_n(params, ['clOrdIDs', 'clientOrderIds', 'client_order_ids'])
params = self.omit(params, ['clOrdIDs', 'clientOrderIds', 'client_order_ids'])
request: dict = {}
response = None
if clientOrderIds:
request['client_order_ids'] = ','.join(clientOrderIds)
response = await self.v1PrivateDeleteClientBatchOrder(self.extend(request, params))
else:
request['order_ids'] = ','.join(ids)
response = await self.v1PrivateDeleteBatchOrder(self.extend(request, params))
#
# {
# "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={}):
"""
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/cancel-all-pending-algo-orders
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/cancel-orders-in-bulk
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 <https://docs.ccxt.com/#/?id=order-structure>`
"""
await self.load_markets()
trigger = self.safe_bool_2(params, 'stop', 'trigger')
params = self.omit(params, ['stop', 'trigger'])
request: dict = {}
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
response = None
if trigger:
response = await self.v1PrivateDeleteAlgoOrders(self.extend(request, params))
else:
response = await self.v1PrivateDeleteOrders(self.extend(request, params))
# 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={}):
"""
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/get-order-by-order_id
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/get-order-by-client_order_id
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/get-algo-order-by-order_id
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=order-structure>`
"""
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: dict = {}
clientOrderId = self.safe_string_n(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
params = self.omit(params, ['stop', 'trigger', 'clOrdID', 'clientOrderId', 'client_order_id'])
response = None
if trigger:
if clientOrderId:
request['client_order_id'] = clientOrderId
response = await self.v1PrivateGetAlgoClientOrderClientOrderId(self.extend(request, params))
else:
request['oid'] = id
response = await self.v1PrivateGetAlgoOrderOid(self.extend(request, params))
else:
if clientOrderId:
request['client_order_id'] = clientOrderId
response = await self.v1PrivateGetClientOrderClientOrderId(self.extend(request, params))
else:
request['oid'] = id
response = await self.v1PrivateGetOrderOid(self.extend(request, params))
#
# {
# "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_BTC_USDC",
# "side": "BUY",
# "status": "FILLED",
# "total_fee": 0.5,
# "fee_asset": "BTC",
# "client_order_id": 1,
# "average_executed_price": 0.67772,
# "created_time": 1653563963000,
# "updated_time": 1653564213000,
# "realized_pnl": 123
# }
# }
#
orders = self.safe_dict(response, 'data', response)
return self.parse_order(orders, market)
async def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
"""
fetches information on multiple orders made by the user
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/get-orders
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=order-structure>`
"""
await self.load_markets()
paginate = False
isTrigger = self.safe_bool_2(params, 'stop', 'trigger', False)
maxLimit = 100 if (isTrigger) else 500
paginate, params = self.handle_option_and_params(params, 'fetchOrders', 'paginate')
if paginate:
return await self.fetch_paginated_call_incremental('fetchOrders', symbol, since, limit, params, 'page', maxLimit)
request: dict = {}
market: Market = None
params = self.omit(params, ['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'
request, params = self.handle_until_option('end_t', request, params)
response = None
if isTrigger:
response = await self.v1PrivateGetAlgoOrders(self.extend(request, params))
else:
response = await self.v1PrivateGetOrders(self.extend(request, params))
#
# {
# "success": True,
# "timestamp": 1702989203989,
# "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_BTC_USDC",
# "side": "BUY",
# "status": "FILLED",
# "total_fee": 0.5,
# "fee_asset": "BTC",
# "client_order_id": 1,
# "average_executed_price": 0.67772,
# "created_time": 1653563963000,
# "updated_time": 1653564213000,
# "realized_pnl": 123
# }]
# }
# }
#
data = self.safe_value(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={}) -> List[Order]:
"""
fetches information on multiple orders made by the user
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/get-orders
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=order-structure>`
"""
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={}) -> List[Order]:
"""
fetches information on multiple orders made by the user
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/get-orders
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=order-structure>`
"""
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={}):
"""
fetch all the trades made from a single order
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=trade-structure>`
"""
await self.load_markets()
market: Market = None
if symbol is not None:
market = self.market(symbol)
request: dict = {
'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={}):
"""
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=trade-structure>`
"""
await self.load_markets()
paginate = False
paginate, params = self.handle_option_and_params(params, 'fetchMyTrades', 'paginate')
if paginate:
return await self.fetch_paginated_call_incremental('fetchMyTrades', symbol, since, limit, params, 'page', 500)
request: dict = {}
market: 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
request, params = self.handle_until_option('end_t', request, params)
response = await self.v1PrivateGetTrades(self.extend(request, params))
#
# {
# "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, params)
def parse_balance(self, response) -> Balances:
result: dict = {
'info': response,
}
balances = self.safe_list(response, 'holding', [])
for i in range(0, len(balances)):
balance = 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')
result[code] = account
return self.safe_balance(result)
async def fetch_balance(self, params={}) -> Balances:
"""
query for balance and get the amount of funds available for trading or funds locked in orders
https://orderly.network/docs/build-on-evm/evm-api/restful-api/private/get-current-holding
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
"""
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={}) -> Any:
await self.load_markets()
request: dict = {}
currency: Currency = None
if code is not None:
currency = self.currency(code)
request['balance_token'] = 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')
params = self.omit(params, 'type')
if transactionType is not None:
request['type'] = transactionType
response = await self.v1PrivateGetAssetHistory(self.extend(request, params))
#
# {
# "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', {})
return [currency, self.safe_list(data, '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)
currency = 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,
}, currency)
def parse_ledger_entry_type(self, type):
types: dict = {
'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={}) -> 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-evm/evm-api/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 <https://docs.ccxt.com/#/?id=ledger>`
"""
currencyRows = await self.get_asset_history_rows(code, since, limit, params)
currency = self.safe_value(currencyRows, 0)
rows = self.safe_list(currencyRows, 1)
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):
statuses: dict = {
'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={}) -> List[Transaction]:
"""
fetch all deposits made to an account
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=transaction-structure>`
"""
request: dict = {
'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={}) -> List[Transaction]:
"""
fetch all withdrawals made from an account
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=transaction-structure>`
"""
request: dict = {
'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={}) -> List[Transaction]:
"""
fetch history of deposits and withdrawals
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=transaction-structure>`
"""
request: dict = {}
currencyRows = await self.get_asset_history_rows(code, since, limit, self.extend(request, params))
currency = self.safe_value(currencyRows, 0)
rows = self.safe_list(currencyRows, 1)
#
# {
# "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={}):
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):
return '0x' + self.hash(message, 'keccak', 'hex')
def sign_hash(self, hash, privateKey):
signature = self.ecdsa(hash[-64:], privateKey[-64:], 'secp256k1', None)
r = signature['r']
s = 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, privateKey):
return self.sign_hash(self.hash_message(message), privateKey[-64:])
async def withdraw(self, code: str, amount: float, address: str, tag: Str = None, params={}) -> Transaction:
"""
make a withdrawal
https://orderly.network/docs/build-on-evm/evm-api/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 str tag:
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
"""
await self.load_markets()
self.check_address(address)
if code is not None:
code = code.upper()
if code != 'USDC':
raise NotSupported(self.id + ' withdraw() only support USDC')
currency = self.currency(code)
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: dict = {
'chainId': chainId,
'name': 'Orderly',
'verifyingContract': verifyingContractAddress,
'version': '1',
}
messageTypes: dict = {
'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: dict = {
'brokerId': self.safe_string(self.options, 'keyBrokerId', 'mode'),
'chainId': self.parse_to_int(chainId),
'receiver': address,
'token': code,
'amount': str(amount),
'withdrawNonce': withdrawNonce,
'timestamp': nonce,
}
msg = self.eth_encode_structured_data(domain, messageTypes, withdrawRequest)
signature = self.sign_message(msg, self.privateKey)
request: dict = {
'signature': signature,
'userAddress': address,
'verifyingContract': verifyingContractAddress,
'message': withdrawRequest,
}
params = self.omit(params, 'chainId')
response = await self.v1PrivatePostWithdrawRequest(self.extend(request, params))
#
# {
# "success": True,
# "timestamp": 1702989203989,
# "data": {
# "withdraw_id": 123
# }
# }
#
data = self.safe_dict(response, 'data', {})
return self.parse_transaction(data, currency)
def parse_leverage(self, leverage, market=None) -> Leverage:
leverageValue = self.safe_integer(leverage, 'max_leverage')
return {
'info': leverage,
'symbol': market['symbol'],
'marginMode': None,
'longLeverage': leverageValue,
'shortLeverage': leverageValue,
}
async def fetch_leverage(self, symbol: str, params={}) -> Leverage:
"""
fetch the set leverage for a market
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=leverage-structure>`
"""
await self.load_markets()
market = self.market(symbol)
response = await self.v1PrivateGetClientInfo(params)
#
# {
# "success": True,
# "timestamp": 1702989203989,
# "data": {
# "account_id": "<string>",
# "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={}):
"""
set the level of leverage for a market
https://orderly.network/docs/build-on-evm/evm-api/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
"""
await self.load_markets()
isMinLeverage = leverage < 1
isMaxLeverage = leverage > 50
if isMinLeverage or isMaxLeverage:
raise BadRequest(self.id + ' leverage should be between 1 and 50')
request: dict = {
'leverage': leverage,
}
return await self.v1PrivatePostClientLeverage(self.extend(request, params))
def parse_position(self, position: dict, market: Market = None):
#
# {
# "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')
market = self.safe_market(contract, market)
size = self.safe_string(position, 'position_qty')
side: Str = None
if Precise.string_gt(size, '0'):
side = 'long'
else:
side = 'short'
contractSize = self.safe_string(market, '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(market, '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',
'marginType': None,
'side': side,
'percentage': None,
'hedged': None,
'stopLossPrice': None,
'takeProfitPrice': None,
})
async def fetch_position(self, symbol: Str, params={}):
"""
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=position-structure>`
"""
await self.load_markets()
market = self.market(symbol)
request: dict = {
'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={}) -> List[Position]:
"""
fetch all open positions
https://orderly.network/docs/build-on-evm/evm-api/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 <https://docs.ccxt.com/#/?id=position-structure>`
"""
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):
return self.milliseconds()
def sign(self, path, section='public', method='GET', params={}, headers=None, body=None):
version = section[0]
access = section[1]
pathWithParams = self.implode_params(path, params)
url = self.implode_hostname(self.urls['api'][access])
url += '/' + version + '/'
params = self.omit(params, self.extract_params(path))
params = self.keysort(params)
if access == 'public':
url += pathWithParams
if params:
url += '?' + self.urlencode(params)
else:
self.check_required_credentials()
isPostOrPut = method == 'POST' or method == 'PUT'
isOrder = path == 'algo/order' or path == 'order' or path == 'batch-order'
if isPostOrPut and isOrder:
isSandboxMode = self.safe_bool(self.options, 'sandboxMode', False)
if not isSandboxMode:
brokerId = self.safe_string(self.options, 'brokerId', 'CCXTMODE')
if path == 'batch-order':
ordersList = self.safe_list(params, 'orders', [])
for i in range(0, len(ordersList)):
params['orders'][i]['order_tag'] = brokerId
else:
params['order_tag'] = brokerId
params = self.keysort(params)
auth = ''
ts = str(self.nonce())
url += pathWithParams
apiKey = self.apiKey
if apiKey.find('ed25519:') < 0:
apiKey = 'ed25519:' + apiKey
headers = {
'orderly-account-id': self.accountId,
'orderly-key': apiKey,
'orderly-timestamp': ts,
}
auth = ts + method + '/' + version + '/' + pathWithParams
if method == 'POST' or method == 'PUT':
body = self.json(params)
auth += body
headers['content-type'] = 'application/json'
else:
if params:
url += '?' + self.urlencode(params)
auth += '?' + self.rawencode(params)
headers['content-type'] = 'application/x-www-form-urlencoded'
if method == 'DELETE':
body = ''
secret = self.secret
if secret.find('ed25519:') >= 0:
parts = secret.split('ed25519:')
secret = parts[1]
signature = self.eddsa(self.encode(auth), self.base58_to_binary(secret), 'ed25519')
headers['orderly-signature'] = self.urlencode_base64(self.base64_to_binary(signature))
return {'url': url, 'method': method, 'body': body, 'headers': headers}
def handle_errors(self, httpCode: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
if not response:
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')
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