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

4048 lines
178 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.base.exchange import Exchange
from ccxt.abstract.woo import ImplicitAPI
import hashlib
from ccxt.base.types import Account, Any, Balances, Bool, Conversion, Currencies, Currency, DepositAddress, Int, LedgerEntry, Leverage, MarginModification, Market, MarketType, Num, Order, OrderBook, OrderSide, OrderType, Position, Str, Strings, FundingRate, FundingRates, Trade, TradingFeeInterface, TradingFees, Transaction, TransferEntry
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 InvalidOrder
from ccxt.base.errors import NotSupported
from ccxt.base.errors import OperationFailed
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import OnMaintenance
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise
class woo(Exchange, ImplicitAPI):
def describe(self) -> Any:
return self.deep_extend(super(woo, self).describe(), {
'id': 'woo',
'name': 'WOO X',
'countries': ['KY'], # Cayman Islands
'rateLimit': 100,
'version': 'v1',
'certified': True,
'pro': True,
'hostname': 'woox.io',
'has': {
'CORS': None,
'spot': True,
'margin': True,
'swap': True,
'future': False,
'option': False,
'addMargin': True,
'cancelAllOrders': True,
'cancelAllOrdersAfter': True,
'cancelOrder': True,
'cancelWithdraw': False, # exchange have that endpoint disabled atm, but was once implemented in ccxt per old docs: https://docx.woo.io/wootrade-documents/#cancel-withdraw-request
'closeAllPositions': False,
'closePosition': False,
'createConvertTrade': True,
'createDepositAddress': False,
'createMarketBuyOrderWithCost': True,
'createMarketOrder': False,
'createMarketOrderWithCost': False,
'createMarketSellOrderWithCost': True,
'createOrder': True,
'createOrderWithTakeProfitAndStopLoss': True,
'createReduceOnlyOrder': True,
'createStopLimitOrder': False,
'createStopLossOrder': True,
'createStopMarketOrder': False,
'createStopOrder': False,
'createTakeProfitOrder': True,
'createTrailingAmountOrder': True,
'createTrailingPercentOrder': True,
'createTriggerOrder': True,
'fetchAccounts': True,
'fetchBalance': True,
'fetchCanceledOrders': False,
'fetchClosedOrder': False,
'fetchClosedOrders': True,
'fetchConvertCurrencies': True,
'fetchConvertQuote': True,
'fetchConvertTrade': True,
'fetchConvertTradeHistory': True,
'fetchCurrencies': True,
'fetchDepositAddress': True,
'fetchDepositAddresses': False,
'fetchDepositAddressesByNetwork': 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,
'fetchPositionHistory': False,
'fetchPositionMode': False,
'fetchPositions': True,
'fetchPositionsHistory': False,
'fetchPremiumIndexOHLCV': False,
'fetchStatus': True,
'fetchTicker': False,
'fetchTickers': False,
'fetchTime': True,
'fetchTrades': True,
'fetchTradingFee': True,
'fetchTradingFees': True,
'fetchTransactions': 'emulated',
'fetchTransfers': True,
'fetchWithdrawals': True,
'reduceMargin': False,
'sandbox': True,
'setLeverage': True,
'setMargin': False,
'setPositionMode': True,
'transfer': True,
'withdraw': True, # exchange have that endpoint disabled atm, but was once implemented in ccxt per old docs: https://docx.woo.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://user-images.githubusercontent.com/1294454/150730761-1a00e5e0-d28c-480f-9e65-089ce3e6ef3b.jpg',
'api': {
'pub': 'https://api-pub.woox.io',
'public': 'https://api.{hostname}',
'private': 'https://api.{hostname}',
},
'test': {
'pub': 'https://api-pub.staging.woox.io',
'public': 'https://api.staging.woox.io',
'private': 'https://api.staging.woox.io',
},
'www': 'https://woox.io/',
'doc': [
'https://docs.woox.io/',
],
'fees': [
'https://support.woox.io/hc/en-001/articles/4404611795353--Trading-Fees',
],
'referral': {
'url': 'https://woox.io/register?ref=DIJT0CNL',
'discount': 0.35,
},
},
'api': {
'v1': {
'pub': {
'get': {
'hist/kline': 10,
'hist/trades': 10,
},
},
'public': {
'get': {
'info': 1,
'info/{symbol}': 1,
'system_info': 1,
'market_trades': 1,
'token': 1,
'token_network': 1,
'funding_rates': 1,
'funding_rate/{symbol}': 1,
'funding_rate_history': 1,
'futures': 1,
'futures/{symbol}': 1,
'orderbook/{symbol}': 1,
'kline': 1,
},
},
'private': {
'get': {
'client/token': 1,
'order/{oid}': 1,
'client/order/{client_order_id}': 1,
'orders': 1,
'client/trade/{tid}': 1,
'order/{oid}/trades': 1,
'client/trades': 1,
'client/hist_trades': 1,
'staking/yield_history': 1,
'client/holding': 1,
'asset/deposit': 10,
'asset/history': 60,
'sub_account/all': 60,
'sub_account/assets': 60,
'sub_account/asset_detail': 60,
'sub_account/ip_restriction': 10,
'asset/main_sub_transfer_history': 30,
'token_interest': 60,
'token_interest/{token}': 60,
'interest/history': 60,
'interest/repay': 60,
'funding_fee/history': 30,
'positions': 3.33, # 30 requests per 10 seconds
'position/{symbol}': 3.33,
'client/transaction_history': 60,
'client/futures_leverage': 60,
},
'post': {
'order': 1, # 10 requests per 1 second per symbol
'order/cancel_all_after': 1,
'asset/ltv': 30,
'asset/internal_withdraw': 30,
'interest/repay': 60,
'client/account_mode': 120,
'client/position_mode': 5,
'client/leverage': 120,
'client/futures_leverage': 30,
'client/isolated_margin': 30,
},
'delete': {
'order': 1,
'client/order': 1,
'orders': 1,
'asset/withdraw': 120, # implemented in ccxt, disabled on the exchange side https://docx.woo.io/wootrade-documents/#cancel-withdraw-request
},
},
},
'v2': {
'private': {
'get': {
'client/holding': 1,
},
},
},
'v3': {
'public': {
'get': {
'systemInfo': 1, # 10/1s
'instruments': 1, # 10/1s
'token': 1, # 10/1s
'tokenNetwork': 1, # 10/1s
'tokenInfo': 1, # 10/1s
'marketTrades': 1, # 10/1s
'marketTradesHistory': 1, # 10/1s
'orderbook': 1, # 10/1s
'kline': 1, # 10/1s
'klineHistory': 1, # 10/1s
'futures': 1, # 10/1s
'fundingRate': 1, # 10/1s
'fundingRateHistory': 1, # 10/1s
'insuranceFund': 1, # 10/1s
},
},
'private': {
'get': {
'trade/order': 2, # 5/1s
'trade/orders': 1, # 10/1s
'trade/algoOrder': 1, # 10/1s
'trade/algoOrders': 1, # 10/1s
'trade/transaction': 1, # 10/1s
'trade/transactionHistory': 5, # 2/1s
'trade/tradingFee': 5, # 2/1s
'account/info': 60, # 10/60s
'account/tokenConfig': 1, # 10/1s
'account/symbolConfig': 1, # 10/1s
'account/subAccounts/all': 60, # 10/60s
'account/referral/summary': 60, # 10/60s
'account/referral/rewardHistory': 60, # 10/60s
'account/credentials': 60, # 10/60s
'asset/balances': 1, # 10/1s
'asset/token/history': 60, # 10/60s
'asset/transfer/history': 30, # 20/60s
'asset/wallet/history': 60, # 10/60s
'asset/wallet/deposit': 60, # 10/60s
'asset/staking/yieldHistory': 60, # 10/60s
'futures/positions': 3.33, # 30/10s
'futures/leverage': 60, # 10/60s
'futures/defaultMarginMode': 60, # 10/60s
'futures/fundingFee/history': 30, # 20/60s
'spotMargin/interestRate': 60, # 10/60s
'spotMargin/interestHistory': 60, # 10/60s
'spotMargin/maxMargin': 60, # 10/60s
'algo/order/{oid}': 1,
'algo/orders': 1,
'positions': 3.33,
'buypower': 1,
'convert/exchangeInfo': 1,
'convert/assetInfo': 1,
'convert/rfq': 60,
'convert/trade': 1,
'convert/trades': 1,
},
'post': {
'trade/order': 2, # 5/1s
'trade/algoOrder': 5, # 2/1s
'trade/cancelAllAfter': 1, # 10/1s
'account/tradingMode': 120, # 5/60s
'account/listenKey': 20, # 5/10s
'asset/transfer': 30, # 20/60s
'asset/wallet/withdraw': 60, # 10/60s
'spotMargin/leverage': 120, # 5/60s
'spotMargin/interestRepay': 60, # 10/60s
'algo/order': 5,
'convert/rft': 60,
},
'put': {
'trade/order': 2, # 5/1s
'trade/algoOrder': 2, # 5/1s
'futures/leverage': 60, # 10/60s
'futures/positionMode': 120, # 5/60s
'order/{oid}': 2,
'order/client/{client_order_id}': 2,
'algo/order/{oid}': 2,
'algo/order/client/{client_order_id}': 2,
},
'delete': {
'trade/order': 1, # 10/1s
'trade/orders': 1, # 10/1s
'trade/algoOrder': 1, # 10/1s
'trade/algoOrders': 1, # 10/1s
'trade/allOrders': 1, # 10/1s
'algo/order/{order_id}': 1,
'algo/orders/pending': 1,
'algo/orders/pending/{symbol}': 1,
'orders/pending': 1,
},
},
},
},
'fees': {
'trading': {
'tierBased': True,
'percentage': True,
'maker': self.parse_number('0.0002'),
'taker': self.parse_number('0.0005'),
},
},
'options': {
'timeDifference': 0, # the difference between system clock and exchange clock
'adjustForTimeDifference': False, # controls the adjustment logic upon instantiation
'sandboxMode': False,
'createMarketBuyOrderRequiresPrice': True,
# these network aliases require manual mapping here
'network-aliases-for-tokens': {
'HT': 'ERC20',
'OMG': 'ERC20',
'UATOM': 'ATOM',
'ZRX': 'ZRX',
},
'networks': {
'TRX': 'TRON',
'TRC20': 'TRON',
'ERC20': 'ETH',
'BEP20': 'BSC',
'ARB': 'Arbitrum',
},
'networksById': {
'TRX': 'TRC20',
'TRON': 'TRC20',
},
# override defaultNetworkCodePriorities for a specific currency
'defaultNetworkCodeForCurrencies': {
# 'USDT': 'TRC20',
# 'BTC': 'BTC',
},
'transfer': {
'fillResponseFromRequest': True,
},
'brokerId': 'bc830de7-50f3-460b-9ee0-f430f83f9dad',
},
'features': {
'default': {
'sandbox': True,
'createOrder': {
'marginMode': True,
'triggerPrice': True,
'triggerPriceType': {
'last': True,
'mark': True,
'index': False,
},
'triggerDirection': False,
'stopLossPrice': False, # todo by triggerPrice
'takeProfitPrice': False, # todo by triggerPrice
'attachedStopLossTakeProfit': None,
'timeInForce': {
'IOC': True,
'FOK': True,
'PO': True,
'GTD': True,
},
'hedged': False,
'trailing': True,
'leverage': False,
'marketBuyByCost': True,
'marketBuyRequiresPrice': False,
'selfTradePrevention': False,
'iceberg': True, # todo implement
},
'createOrders': None,
'fetchMyTrades': {
'marginMode': False,
'limit': 500,
'daysBack': 90,
'untilDays': 10000,
'symbolRequired': False,
},
'fetchOrder': {
'marginMode': False,
'trigger': True,
'trailing': False,
'symbolRequired': False,
},
'fetchOpenOrders': {
'marginMode': False,
'limit': 500,
'trigger': True,
'trailing': True,
'symbolRequired': False,
},
'fetchOrders': {
'marginMode': False,
'limit': 500,
'daysBack': None,
'untilDays': 100000,
'trigger': True,
'trailing': True,
'symbolRequired': False,
},
'fetchClosedOrders': {
'marginMode': False,
'limit': 500,
'daysBack': None,
'daysBackCanceled': None,
'untilDays': 100000,
'trigger': True,
'trailing': True,
'symbolRequired': False,
},
'fetchOHLCV': {
'limit': 1000,
},
},
'spot': {
'extends': 'default',
},
'forSwap': {
'extends': 'default',
'createOrder': {
'hedged': True,
},
},
'swap': {
'linear': {
'extends': 'forSwap',
},
'inverse': None,
},
'future': {
'linear': None,
'inverse': None,
},
},
'commonCurrencies': {},
'exceptions': {
'exact': {
'-1000': OperationFailed, # {"code": -1000, "message": "An unknown error occurred while processing the request"} or {"success":false,"code":"-1000","message":"An internal error has occurred. We are unable to process your request. Please try again later."}
'-1001': AuthenticationError, # {"code": -1001, "message": "The api key or secret is in wrong format"}
'-1002': AuthenticationError, # {"code": -1002, "message": "API key or secret is invalid, it may because key have insufficient permission or the key is expired/revoked."}
'-1003': RateLimitExceeded, # {"code": -1003, "message": "Rate limit exceed."}
'-1004': BadRequest, # {"code": -1004, "message": "An unknown parameter was sent."}
'-1005': BadRequest, # {"code": -1005, "message": "Some parameters are in wrong format for api."}
'-1006': BadRequest, # {"code": -1006, "message": "The data is not found in server."}
'-1007': BadRequest, # {"code": -1007, "message": "The data is already exists or your request is duplicated."}
'-1008': InvalidOrder, # {"code": -1008, "message": "The quantity of settlement is too high than you can request."}
'-1009': BadRequest, # {"code": -1009, "message": "Can not request withdrawal settlement, you need to deposit other arrears first."}
'-1012': BadRequest, # {"code": -1012, "message": "Amount is required for buy market orders when margin disabled."} 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': InvalidOrder, # {"code": -1101, "message": "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, # {"code": -1102, "message": "The order value(price * size) is too small."}
'-1103': InvalidOrder, # {"code": -1103, "message": "The order price is not following the tick size rule for the symbol."}
'-1104': InvalidOrder, # {"code": -1104, "message": "The order quantity is not following the step size rule for the symbol."}
'-1105': InvalidOrder, # {"code": -1105, "message": "Price is X% too high or X% too low from the mid price."}
},
'broad': {
'Can not place': ExchangeError, # {"code": -1011, "message": "Can not place/cancel orders, it may because internal network error. Please try again in a few seconds."}
'maintenance': OnMaintenance, # {"code":"-1011","message":"The system is under maintenance.","success":false}
'symbol must not be blank': BadRequest, # when sending 'cancelOrder' without symbol [-1005]
'The token is not supported': BadRequest, # when getting incorrect token's deposit address [-1005]
'Your order and symbol are not valid or already canceled': BadRequest, # actual response whensending 'cancelOrder' for already canceled id [-1006]
'Insufficient WOO. Please enable margin trading for leverage trading': BadRequest, # when selling insufficent token [-1012]
},
},
'precisionMode': TICK_SIZE,
})
def fetch_status(self, params={}):
"""
the latest known information on the availability of the exchange API
https://developer.woox.io/api-reference/endpoint/public_data/systemInfo
: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 = self.v3PublicGetSystemInfo(params)
#
# {
# "success": True,
# "data": {
# "status": 0,
# "msg": "System is functioning properly.",
# "estimatedEndTime": 1749963600362
# },
# "timestamp": 1751442989564
# }
#
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,
}
def fetch_time(self, params={}) -> Int:
"""
fetches the current integer timestamp in milliseconds from the exchange server
https://developer.woox.io/api-reference/endpoint/public_data/systemInfo
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns int: the current integer timestamp in milliseconds from the exchange server
"""
response = self.v3PublicGetSystemInfo(params)
#
# {
# "success": True,
# "data": {
# "status": 0,
# "msg": "System is functioning properly.",
# "estimatedEndTime": 1749963600362
# },
# "timestamp": 1751442989564
# }
#
return self.safe_integer(response, 'timestamp')
def fetch_markets(self, params={}) -> List[Market]:
"""
retrieves data on all markets for woo
https://developer.woox.io/api-reference/endpoint/public_data/instruments
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: an array of objects representing market data
"""
if self.options['adjustForTimeDifference']:
self.load_time_difference()
response = self.v3PublicGetInstruments(params)
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "symbol": "SPOT_AAVE_USDT",
# "status": "TRADING",
# "baseAsset": "AAVE",
# "baseAssetMultiplier": 1,
# "quoteAsset": "USDT",
# "quoteMin": "0",
# "quoteMax": "100000",
# "quoteTick": "0.01",
# "baseMin": "0.005",
# "baseMax": "5000",
# "baseTick": "0.0001",
# "minNotional": "1",
# "bidCapRatio": "1.1",
# "bidFloorRatio": null,
# "askCapRatio": null,
# "askFloorRatio": "0.9",
# "orderMode": "NORMAL",
# "impactNotional": null,
# "isAllowedRpi": False,
# "tickGranularity": null
# }
# ]
# },
# "timestamp": 1751512951338
# }
#
data = self.safe_dict(response, 'data', {})
rows = self.safe_list(data, 'rows', [])
return self.parse_markets(rows)
def parse_market(self, market: dict) -> Market:
marketId = self.safe_string(market, 'symbol')
parts = marketId.split('_')
first = self.safe_string(parts, 0)
marketType: MarketType
spot = False
swap = False
if first == 'SPOT':
spot = True
marketType = 'spot'
elif first == 'PERP':
swap = True
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 = None
settle: Str = None
symbol = base + '/' + quote
contractSize: Num = None
linear: Bool = None
inverse: Bool = None
margin = True
contract = swap
if contract:
margin = False
settleId = self.safe_string(parts, 2)
settle = self.safe_currency_code(settleId)
symbol = base + '/' + quote + ':' + settle
contractSize = self.parse_number('1')
linear = True
inverse = False
active = self.safe_string(market, 'status') == 'TRADING'
return {
'id': marketId,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': settle,
'baseId': baseId,
'quoteId': quoteId,
'settleId': settleId,
'type': marketType,
'spot': spot,
'margin': margin,
'swap': swap,
'future': False,
'option': False,
'active': active,
'contract': contract,
'linear': linear,
'inverse': inverse,
'contractSize': contractSize,
'expiry': None,
'expiryDatetime': None,
'strike': None,
'optionType': None,
'precision': {
'amount': self.safe_number(market, 'baseTick'),
'price': self.safe_number(market, 'quoteTick'),
},
'limits': {
'leverage': {
'min': None,
'max': None,
},
'amount': {
'min': self.safe_number(market, 'baseMin'),
'max': self.safe_number(market, 'baseMax'),
},
'price': {
'min': self.safe_number(market, 'quoteMin'),
'max': self.safe_number(market, 'quoteMax'),
},
'cost': {
'min': self.safe_number(market, 'minNotional'),
'max': None,
},
},
'created': None,
'info': market,
}
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://developer.woox.io/api-reference/endpoint/public_data/marketTrades
: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>`
"""
self.load_markets()
market = self.market(symbol)
request: dict = {
'symbol': market['id'],
}
if limit is not None:
request['limit'] = limit
response = self.v3PublicGetMarketTrades(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "symbol": "SPOT_BTC_USDT",
# "side": "SELL",
# "source": 0,
# "executedPrice": "108741.01",
# "executedQuantity": "0.02477",
# "executedTimestamp": 1751513940144
# }
# ]
# },
# "timestamp": 1751513988543
# }
#
data = self.safe_dict(response, 'data', {})
rows = self.safe_list(data, 'rows', [])
return self.parse_trades(rows, market, since, limit)
def parse_trade(self, trade: dict, market: Market = None) -> Trade:
#
# public/market_trades
#
# {
# "symbol": "SPOT_BTC_USDT",
# "side": "SELL",
# "source": 0,
# "executedPrice": "108741.01",
# "executedQuantity": "0.02477",
# "executedTimestamp": 1751513940144
# }
#
# fetchOrderTrades, fetchOrder
#
# {
# "id": 1734947821,
# "symbol": "SPOT_LTC_USDT",
# "orderId": 60780383217,
# "executedPrice": 87.86,
# "executedQuantity": 0.1,
# "fee": 0.0001,
# "realizedPnl": null,
# "feeAsset": "LTC",
# "orderTag": "default",
# "side": "BUY",
# "executedTimestamp": "1752055173.630",
# "isMaker": 0
# }
#
isFromFetchOrder = ('id' in trade)
timestampString = self.safe_string_2(trade, 'executed_timestamp', 'executedTimestamp')
timestamp = None
if timestampString is not None:
if timestampString.find('.') > -1:
timestamp = self.safe_timestamp_2(trade, 'executed_timestamp', 'executedTimestamp')
else:
timestamp = self.safe_integer(trade, 'executedTimestamp')
marketId = self.safe_string(trade, 'symbol')
market = self.safe_market(marketId, market)
symbol = market['symbol']
price = self.safe_string_2(trade, 'executed_price', 'executedPrice')
amount = self.safe_string_2(trade, 'executed_quantity', 'executedQuantity')
order_id = self.safe_string_2(trade, 'order_id', 'orderId')
fee = self.parse_token_and_fee_temp(trade, ['fee_asset', 'feeAsset'], ['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_2(trade, 'is_maker', 'isMaker') == '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)
def parse_token_and_fee_temp(self, item, feeTokenKeys, feeAmountKeys):
feeCost = self.safe_string_n(item, feeAmountKeys)
fee = None
if feeCost is not None:
feeCurrencyId = self.safe_string_n(item, feeTokenKeys)
feeCurrencyCode = self.safe_currency_code(feeCurrencyId)
fee = {
'cost': feeCost,
'currency': feeCurrencyCode,
}
return fee
def parse_trading_fee(self, fee: dict, market: Market = None) -> TradingFeeInterface:
marketId = self.safe_string(fee, 'symbol')
symbol = self.safe_symbol(marketId, market)
return {
'info': fee,
'symbol': symbol,
'maker': self.parse_number(Precise.string_div(self.safe_string(fee, 'makerFee'), '100')),
'taker': self.parse_number(Precise.string_div(self.safe_string(fee, 'takerFee'), '100')),
'percentage': None,
'tierBased': None,
}
def fetch_trading_fee(self, symbol: str, params={}) -> TradingFeeInterface:
"""
fetch the trading fees for a market
https://developer.woox.io/api-reference/endpoint/trading/get_tradingFee
:param str symbol: unified market symbol
:param dict [params]: extra parameters specific to the exchange API endpoint
:param boolean [params.portfolioMargin]: set to True if you would like to fetch trading fees in a portfolio margin account
:param str [params.subType]: "linear" or "inverse"
:returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
"""
self.load_markets()
market = self.market(symbol)
request: dict = {
'symbol': market['id'],
}
response = self.v3PrivateGetTradeTradingFee(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "symbol": "SPOT_BTC_USDT",
# "takerFee": "10",
# "makerFee": "8"
# },
# "timestamp": 1751858977368
# }
#
data = self.safe_dict(response, 'data', {})
return self.parse_trading_fee(data, market)
def fetch_trading_fees(self, params={}) -> TradingFees:
"""
fetch the trading fees for multiple markets
https://developer.woox.io/api-reference/endpoint/account/get_account_info
: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
"""
self.load_markets()
response = self.v3PrivateGetAccountInfo(params)
#
# {
# "success": True,
# "data": {
# "applicationId": "251bf5c4-f3c8-4544-bb8b-80001007c3c0",
# "account": "carlos_jose_lima@yahoo.com",
# "alias": "carlos_jose_lima@yahoo.com",
# "otpauth": True,
# "accountMode": "FUTURES",
# "positionMode": "ONE_WAY",
# "leverage": 0,
# "makerFeeRate": 0,
# "takerFeeRate": 0,
# "marginRatio": "10",
# "openMarginRatio": "10",
# "initialMarginRatio": "10",
# "maintenanceMarginRatio": "0.03",
# "totalCollateral": "165.55629469",
# "freeCollateral": "165.55629469",
# "totalAccountValue": "167.32418611",
# "totalTradingValue": "167.32418611",
# "totalVaultValue": "0",
# "totalStakingValue": "0",
# "totalLaunchpadValue": "0",
# "totalEarnValue": "0",
# "referrerID": null,
# "accountType": "Main"
# },
# "timestamp": 1752062807915
# }
#
data = self.safe_dict(response, 'data', {})
maker = self.safe_string(data, 'makerFeeRate')
taker = self.safe_string(data, 'takerFeeRate')
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
def fetch_currencies(self, params={}) -> Currencies:
"""
fetches all available currencies on an exchange
https://docs.woox.io/#available-token-public
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an associative dictionary of currencies
"""
result: dict = {}
tokenResponsePromise = self.v1PublicGetToken(params)
#
# {
# "rows": [
# {
# "token": "ETH_USDT",
# "fullname": "Tether",
# "network": "ETH",
# "decimals": "6",
# "delisted": False,
# "balance_token": "USDT",
# "created_time": "1710123398",
# "updated_time": "1746528481",
# "can_collateral": True,
# "can_short": True
# },
# {
# "token": "BSC_USDT",
# "fullname": "Tether",
# "network": "BSC",
# "decimals": "18",
# "delisted": False,
# "balance_token": "USDT",
# "created_time": "1710123395",
# "updated_time": "1746528601",
# "can_collateral": True,
# "can_short": True
# },
# {
# "token": "ALGO",
# "fullname": "Algorand",
# "network": "ALGO",
# "decimals": "6",
# "delisted": False,
# "balance_token": "ALGO",
# "created_time": "1710123394",
# "updated_time": "1723087518",
# "can_collateral": True,
# "can_short": True
# },
# ...
# ],
# "success": True
# }
#
# only make one request for currrencies...
tokenNetworkResponsePromise = self.v1PublicGetTokenNetwork(params)
#
# {
# "rows": [
# {
# "protocol": "ERC20",
# "network": "ETH",
# "token": "USDT",
# "name": "Ethereum(ERC20)",
# "minimum_withdrawal": "10.00000000",
# "withdrawal_fee": "2.00000000",
# "allow_deposit": "1",
# "allow_withdraw": "1"
# },
# {
# "protocol": "TRC20",
# "network": "TRX",
# "token": "USDT",
# "name": "Tron(TRC20)",
# "minimum_withdrawal": "10.00000000",
# "withdrawal_fee": "4.50000000",
# "allow_deposit": "1",
# "allow_withdraw": "1"
# },
# ...
# ],
# "success": True
# }
#
tokenResponse, tokenNetworkResponse = [tokenResponsePromise, tokenNetworkResponsePromise]
tokenRows = self.safe_list(tokenResponse, 'rows', [])
tokenNetworkRows = self.safe_list(tokenNetworkResponse, 'rows', [])
networksById = self.group_by(tokenNetworkRows, 'token')
tokensById = self.group_by(tokenRows, 'balance_token')
currencyIds = list(tokensById.keys())
for i in range(0, len(currencyIds)):
currencyId = currencyIds[i]
code = self.safe_currency_code(currencyId)
tokensByNetworkId = self.index_by(tokensById[currencyId], 'network')
chainsByNetworkId = self.index_by(networksById[currencyId], 'network')
keys = list(chainsByNetworkId.keys())
resultingNetworks: dict = {}
for j in range(0, len(keys)):
networkId = keys[j]
tokenEntry = self.safe_dict(tokensByNetworkId, networkId, {})
networkEntry = self.safe_dict(chainsByNetworkId, networkId, {})
networkCode = self.network_id_to_code(networkId, code)
specialNetworkId = self.safe_string(tokenEntry, 'token')
resultingNetworks[networkCode] = {
'id': networkId,
'currencyNetworkId': specialNetworkId, # exchange uses special crrency-ids(coin + network junction)
'network': networkCode,
'active': None,
'deposit': self.safe_string(networkEntry, 'allow_deposit') == '1',
'withdraw': self.safe_string(networkEntry, 'allow_withdraw') == '1',
'fee': self.safe_number(networkEntry, 'withdrawal_fee'),
'precision': self.parse_number(self.parse_precision(self.safe_string(tokenEntry, 'decimals'))),
'limits': {
'withdraw': {
'min': self.safe_number(networkEntry, 'minimum_withdrawal'),
'max': None,
},
'deposit': {
'min': None,
'max': None,
},
},
'info': [networkEntry, tokenEntry],
}
result[code] = self.safe_currency_structure({
'id': currencyId,
'name': None,
'code': code,
'precision': None,
'active': None,
'fee': None,
'networks': resultingNetworks,
'deposit': None,
'withdraw': None,
'type': 'crypto',
'limits': {
'deposit': {
'min': None,
'max': None,
},
'withdraw': {
'min': None,
'max': None,
},
},
'info': [tokensByNetworkId, chainsByNetworkId],
})
return result
def create_market_buy_order_with_cost(self, symbol: str, cost: float, params={}):
"""
create a market buy order by providing the symbol and cost
https://docs.woox.io/#send-order
:param str symbol: unified symbol of the market to create an order in
:param float cost: how much you want to trade in units of the quote currency
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
"""
self.load_markets()
market = self.market(symbol)
if not market['spot']:
raise NotSupported(self.id + ' createMarketBuyOrderWithCost() supports spot orders only')
return self.create_order(symbol, 'market', 'buy', cost, 1, params)
def create_market_sell_order_with_cost(self, symbol: str, cost: float, params={}):
"""
create a market sell order by providing the symbol and cost
https://docs.woox.io/#send-order
:param str symbol: unified symbol of the market to create an order in
:param float cost: how much you want to trade in units of the quote currency
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
"""
self.load_markets()
market = self.market(symbol)
if not market['spot']:
raise NotSupported(self.id + ' createMarketSellOrderWithCost() supports spot orders only')
return self.create_order(symbol, 'market', 'sell', cost, 1, params)
def create_trailing_amount_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, trailingAmount: Num = None, trailingTriggerPrice: Num = None, params={}) -> Order:
"""
create a trailing order by providing the symbol, type, side, amount, price and trailingAmount
https://docs.woox.io/#send-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 you want to trade in units of the base currency, or number of contracts
:param float [price]: the price for the order to be filled at, in units of the quote currency, ignored in market orders
:param float trailingAmount: the quote amount to trail away from the current market price
:param float trailingTriggerPrice: the price to activate a trailing order, default uses the price argument
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
"""
if trailingAmount is None:
raise ArgumentsRequired(self.id + ' createTrailingAmountOrder() requires a trailingAmount argument')
if trailingTriggerPrice is None:
raise ArgumentsRequired(self.id + ' createTrailingAmountOrder() requires a trailingTriggerPrice argument')
params['trailingAmount'] = trailingAmount
params['trailingTriggerPrice'] = trailingTriggerPrice
return self.create_order(symbol, type, side, amount, price, params)
def create_trailing_percent_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, trailingPercent: Num = None, trailingTriggerPrice: Num = None, params={}) -> Order:
"""
create a trailing order by providing the symbol, type, side, amount, price and trailingPercent
https://docs.woox.io/#send-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 you want to trade in units of the base currency, or number of contracts
:param float [price]: the price for the order to be filled at, in units of the quote currency, ignored in market orders
:param float trailingPercent: the percent to trail away from the current market price
:param float trailingTriggerPrice: the price to activate a trailing order, default uses the price argument
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
"""
if trailingPercent is None:
raise ArgumentsRequired(self.id + ' createTrailingPercentOrder() requires a trailingPercent argument')
if trailingTriggerPrice is None:
raise ArgumentsRequired(self.id + ' createTrailingPercentOrder() requires a trailingTriggerPrice argument')
params['trailingPercent'] = trailingPercent
params['trailingTriggerPrice'] = trailingTriggerPrice
return self.create_order(symbol, type, side, amount, price, params)
def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
"""
create a trade order
https://developer.woox.io/api-reference/endpoint/trading/post_order
https://developer.woox.io/api-reference/endpoint/trading/post_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 str [params.marginMode]: *for swap markets only* 'cross' or 'isolated', default 'cross'
: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 'TRAILING_STOP' or 'OCO' or 'CLOSE_POSITION'
:param float [params.cost]: *spot market buy only* the quote quantity that can be used alternative for the amount
:param str [params.trailingAmount]: the quote amount to trail away from the current market price
:param str [params.trailingPercent]: the percent to trail away from the current market price
:param str [params.trailingTriggerPrice]: the price to trigger a trailing order, default uses the price argument
:param str [params.position_side]: 'SHORT' or 'LONG' - if position mode is HEDGE_MODE and the trading involves futures, then is required, otherwise self parameter is not required
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
"""
reduceOnly = self.safe_bool_2(params, 'reduceOnly', 'reduce_only')
params = self.omit(params, ['reduceOnly', 'reduce_only'])
orderType = type.upper()
self.load_markets()
market = self.market(symbol)
orderSide = side.upper()
request: dict = {
'symbol': market['id'],
'side': orderSide,
}
marginMode: Str = None
marginMode, params = self.handle_margin_mode_and_params('createOrder', params)
if marginMode is not None:
request['marginMode'] = self.encode_margin_mode(marginMode)
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')
trailingTriggerPrice = self.safe_string_2(params, 'trailingTriggerPrice', 'activatedPrice', self.number_to_string(price))
trailingAmount = self.safe_string_2(params, 'trailingAmount', 'callbackValue')
trailingPercent = self.safe_string_2(params, 'trailingPercent', 'callbackRate')
isTrailingAmountOrder = trailingAmount is not None
isTrailingPercentOrder = trailingPercent is not None
isTrailing = isTrailingAmountOrder or isTrailingPercentOrder
isConditional = isTrailing or 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)
clientOrderIdKey = 'clientAlgoOrderId' if isConditional else 'clientOrderId'
request['type'] = orderType # LIMIT/MARKET/IOC/FOK/POST_ONLY/ASK/BID
if not isConditional:
if postOnly:
request['type'] = 'POST_ONLY'
elif timeInForce == 'fok':
request['type'] = 'FOK'
elif timeInForce == 'ioc':
request['type'] = 'IOC'
if reduceOnly:
request['reduceOnly'] = reduceOnly
if not isMarket and price is not None:
request['price'] = self.price_to_precision(symbol, price)
if isMarket and not isConditional:
# for market buy it requires the amount of quote currency to spend
cost = self.safe_string_n(params, ['cost', 'order_amount', 'orderAmount'])
params = self.omit(params, ['cost', 'order_amount', 'orderAmount'])
isPriceProvided = price is not None
if market['spot'] and (isPriceProvided or (cost is not None)):
quoteAmount = None
if cost is not None:
quoteAmount = self.cost_to_precision(symbol, cost)
else:
amountString = self.number_to_string(amount)
priceString = self.number_to_string(price)
costRequest = Precise.string_mul(amountString, priceString)
quoteAmount = self.cost_to_precision(symbol, costRequest)
request['amount'] = quoteAmount
else:
request['quantity'] = self.amount_to_precision(symbol, amount)
elif algoType != 'POSITIONAL_TP_SL':
request['quantity'] = self.amount_to_precision(symbol, amount)
clientOrderId = self.safe_string_n(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
if clientOrderId is not None:
request[clientOrderIdKey] = clientOrderId
if isTrailing:
if trailingTriggerPrice is None:
raise ArgumentsRequired(self.id + ' createOrder() requires a trailingTriggerPrice parameter for trailing orders')
request['activatedPrice'] = self.price_to_precision(symbol, trailingTriggerPrice)
request['algoType'] = 'TRAILING_STOP'
if isTrailingAmountOrder:
request['callbackValue'] = trailingAmount
elif isTrailingPercentOrder:
convertedTrailingPercent = Precise.string_div(trailingPercent, '100')
request['callbackRate'] = convertedTrailingPercent
elif triggerPrice is not None:
if algoType != 'TRAILING_STOP':
request['triggerPrice'] = self.price_to_precision(symbol, triggerPrice)
request['algoType'] = 'STOP'
elif (stopLoss is not None) or (takeProfit is not None):
request['algoType'] = 'BRACKET'
outterOrder: dict = {
'symbol': market['id'],
'reduceOnly': False,
'algoType': 'POSITIONAL_TP_SL',
'childOrders': [],
}
childOrders = outterOrder['childOrders']
closeSide = 'SELL' if (orderSide == 'BUY') else 'BUY'
if stopLoss is not None:
stopLossPrice = self.safe_string(stopLoss, 'triggerPrice', stopLoss)
stopLossOrder: dict = {
'side': closeSide,
'algoType': 'STOP_LOSS',
'triggerPrice': self.price_to_precision(symbol, stopLossPrice),
'type': 'CLOSE_POSITION',
'reduceOnly': True,
}
childOrders.append(stopLossOrder)
if takeProfit is not None:
takeProfitPrice = self.safe_string(takeProfit, 'triggerPrice', takeProfit)
takeProfitOrder: dict = {
'side': closeSide,
'algoType': 'TAKE_PROFIT',
'triggerPrice': self.price_to_precision(symbol, takeProfitPrice),
'type': 'CLOSE_POSITION',
'reduceOnly': True,
}
childOrders.append(takeProfitOrder)
request['childOrders'] = [outterOrder]
params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id', 'postOnly', 'timeInForce', 'stopPrice', 'triggerPrice', 'stopLoss', 'takeProfit', 'trailingPercent', 'trailingAmount', 'trailingTriggerPrice'])
response = None
if isConditional:
response = self.v3PrivatePostTradeAlgoOrder(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "orderId": "1578938",
# "clientOrderId": "0",
# "algoType": "STOP_LOSS",
# "quantity": "0.1"
# }
# ]
# },
# "timestamp": "1686149372216"
# }
#
else:
response = self.v3PrivatePostTradeOrder(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "orderId": 60667653330,
# "clientOrderId": 0,
# "type": "LIMIT",
# "price": 60,
# "quantity": 0.1,
# "amount": null,
# "bidAskLevel": null
# },
# "timestamp": 1751871779855
# }
#
data = self.safe_dict(response, 'data', {})
data = self.safe_dict(self.safe_list(data, 'rows'), 0, data)
data['timestamp'] = self.safe_string(response, 'timestamp')
return self.parse_order(data, market)
def encode_margin_mode(self, mode):
modes = {
'cross': 'CROSS',
'isolated': 'ISOLATED',
}
return self.safe_string(modes, mode, mode)
def edit_order(self, id: str, symbol: str, type: OrderType, side: OrderSide, amount: Num = None, price: Num = None, params={}):
"""
edit a trade order
https://docs.woox.io/#edit-order
https://docs.woox.io/#edit-order-by-client_order_id
https://docs.woox.io/#edit-algo-order
https://docs.woox.io/#edit-algo-order-by-client_order_id
: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
:param str [params.trailingAmount]: the quote amount to trail away from the current market price
:param str [params.trailingPercent]: the percent to trail away from the current market price
:param str [params.trailingTriggerPrice]: the price to trigger a trailing order, default uses the price argument
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
"""
self.load_markets()
market = self.market(symbol)
request: dict = {
# 'quantity': self.amount_to_precision(symbol, amount),
# 'price': self.price_to_precision(symbol, price),
}
if price is not None:
request['price'] = self.price_to_precision(symbol, price)
if amount is not None:
request['quantity'] = self.amount_to_precision(symbol, amount)
clientOrderIdUnified = self.safe_string_2(params, 'clOrdID', 'clientOrderId')
clientOrderIdExchangeSpecific = self.safe_string(params, 'client_order_id', clientOrderIdUnified)
isByClientOrder = clientOrderIdExchangeSpecific is not None
triggerPrice = self.safe_number_n(params, ['triggerPrice', 'stopPrice', 'takeProfitPrice', 'stopLossPrice'])
if triggerPrice is not None:
request['triggerPrice'] = self.price_to_precision(symbol, triggerPrice)
trailingTriggerPrice = self.safe_string_2(params, 'trailingTriggerPrice', 'activatedPrice', self.number_to_string(price))
trailingAmount = self.safe_string_2(params, 'trailingAmount', 'callbackValue')
trailingPercent = self.safe_string_2(params, 'trailingPercent', 'callbackRate')
isTrailingAmountOrder = trailingAmount is not None
isTrailingPercentOrder = trailingPercent is not None
isTrailing = isTrailingAmountOrder or isTrailingPercentOrder
if isTrailing:
if trailingTriggerPrice is not None:
request['activatedPrice'] = self.price_to_precision(symbol, trailingTriggerPrice)
if isTrailingAmountOrder:
request['callbackValue'] = trailingAmount
elif isTrailingPercentOrder:
convertedTrailingPercent = Precise.string_div(trailingPercent, '100')
request['callbackRate'] = convertedTrailingPercent
params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id', 'stopPrice', 'triggerPrice', 'takeProfitPrice', 'stopLossPrice', 'trailingTriggerPrice', 'trailingAmount', 'trailingPercent'])
isConditional = isTrailing or (triggerPrice is not None) or (self.safe_value(params, 'childOrders') is not None)
response = None
if isByClientOrder:
request['client_order_id'] = clientOrderIdExchangeSpecific
if isConditional:
response = self.v3PrivatePutAlgoOrderClientClientOrderId(self.extend(request, params))
else:
response = self.v3PrivatePutOrderClientClientOrderId(self.extend(request, params))
else:
request['oid'] = id
if isConditional:
response = self.v3PrivatePutAlgoOrderOid(self.extend(request, params))
else:
response = self.v3PrivatePutOrderOid(self.extend(request, params))
#
# {
# "code": 0,
# "data": {
# "status": "string",
# "success": True
# },
# "message": "string",
# "success": True,
# "timestamp": 0
# }
#
data = self.safe_dict(response, 'data', {})
return self.parse_order(data, market)
def cancel_order(self, id: str, symbol: Str = None, params={}):
"""
https://developer.woox.io/api-reference/endpoint/trading/cancel_order
https://developer.woox.io/api-reference/endpoint/trading/cancel_algo_order
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 trigger/algo order
:returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
"""
isTrigger = self.safe_bool_2(params, 'trigger', 'stop', False)
params = self.omit(params, ['trigger', 'stop'])
if not isTrigger and (symbol is None):
raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
self.load_markets()
market: Market = None
if symbol is not None:
market = self.market(symbol)
request: dict = {}
clientOrderIdUnified = self.safe_string_2(params, 'clOrdID', 'clientOrderId')
clientOrderIdExchangeSpecific = self.safe_string(params, 'client_order_id', clientOrderIdUnified)
params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
isByClientOrder = clientOrderIdExchangeSpecific is not None
response = None
if isTrigger:
if isByClientOrder:
request['clientAlgoOrderId'] = clientOrderIdExchangeSpecific
else:
request['algoOrderId'] = id
response = self.v3PrivateDeleteTradeAlgoOrder(self.extend(request, params))
else:
request['symbol'] = market['id']
if isByClientOrder:
request['clientOrderId'] = clientOrderIdExchangeSpecific
else:
request['orderId'] = id
response = self.v3PrivateDeleteTradeOrder(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "status": "CANCEL_SENT"
# },
# "timestamp": 1751940315838
# }
#
data = self.safe_dict(response, 'data', {})
data['timestamp'] = self.safe_string(response, 'timestamp')
if isByClientOrder:
data['clientOrderId'] = clientOrderIdExchangeSpecific
else:
data['orderId'] = id
return self.parse_order(data, market)
def cancel_all_orders(self, symbol: Str = None, params={}):
"""
https://developer.woox.io/api-reference/endpoint/trading/cancel_all_order
https://developer.woox.io/api-reference/endpoint/trading/cancel_algo_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 trigger/algo order
:returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
"""
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 = self.v3PrivateDeleteTradeAlgoOrders(params)
else:
response = self.v3PrivateDeleteTradeOrders(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "status": "CANCEL_ALL_SENT"
# },
# "timestamp": 1751941988134
# }
#
data = self.safe_dict(response, 'data', {})
return [self.safe_order({'info': data})]
def cancel_all_orders_after(self, timeout: Int, params={}):
"""
dead man's switch, cancel all orders after the given timeout
https://developer.woox.io/api-reference/endpoint/trading/cancel_all_after
:param number timeout: time in milliseconds, 0 represents cancel the timer
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: the api result
"""
self.load_markets()
request: dict = {
'triggerAfter': min(timeout, 900000) if (timeout > 0) else 0,
}
response = self.v3PrivatePostTradeCancelAllAfter(self.extend(request, params))
#
# {
# "success": True,
# "timestamp": 123,
# "data": {
# "expectedTriggerTime": 123
# }
# }
#
return response
def fetch_order(self, id: str, symbol: Str = None, params={}):
"""
https://developer.woox.io/api-reference/endpoint/trading/get_order
https://developer.woox.io/api-reference/endpoint/trading/get_algo_order
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 trigger/algo order
:returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
"""
self.load_markets()
market = None
if symbol is not None:
market = self.market(symbol)
trigger = self.safe_bool_2(params, 'stop', 'trigger')
params = self.omit(params, ['stop', 'trigger'])
request: dict = {}
clientOrderId = self.safe_string_2(params, 'clOrdID', 'clientOrderId')
response = None
if trigger:
if clientOrderId is not None:
request['clientAlgoOrderId'] = id
else:
request['algoOrderId'] = id
response = self.v3PrivateGetTradeAlgoOrder(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "algoOrderId": 10399260,
# "clientAlgoOrderId": 0,
# "rootAlgoOrderId": 10399260,
# "parentAlgoOrderId": 0,
# "symbol": "SPOT_LTC_USDT",
# "algoOrderTag": "default",
# "algoType": "TAKE_PROFIT",
# "side": "BUY",
# "quantity": 0.1,
# "isTriggered": False,
# "triggerPrice": 65,
# "triggerStatus": "USELESS",
# "type": "LIMIT",
# "rootAlgoStatus": "NEW",
# "algoStatus": "NEW",
# "triggerPriceType": "MARKET_PRICE",
# "price": 60,
# "triggerTime": "0",
# "totalExecutedQuantity": 0,
# "visibleQuantity": 0.1,
# "averageExecutedPrice": 0,
# "totalFee": 0,
# "feeAsset": "",
# "totalRebate": 0,
# "rebateAsset": "",
# "reduceOnly": False,
# "createdTime": "1752049747.732",
# "updatedTime": "1752049747.732",
# "positionSide": "BOTH"
# },
# "timestamp": 1752049767550
# }
#
else:
if clientOrderId is not None:
request['clientOrderId'] = clientOrderId
else:
request['orderId'] = id
response = self.v3PrivateGetTradeOrder(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "orderId": 60780315704,
# "clientOrderId": 0,
# "symbol": "SPOT_LTC_USDT",
# "orderTag": "default",
# "side": "BUY",
# "quantity": 0.1,
# "amount": null,
# "type": "LIMIT",
# "status": "NEW",
# "price": 60,
# "executed": 0,
# "visible": 0.1,
# "averageExecutedPrice": 0,
# "totalFee": 0,
# "feeAsset": "LTC",
# "totalRebate": 0,
# "rebateAsset": "USDT",
# "reduceOnly": False,
# "createdTime": "1752049062.496",
# "realizedPnl": null,
# "positionSide": "BOTH",
# "bidAskLevel": null
# },
# "timestamp": 1752049393466
# }
#
data = self.safe_dict(response, 'data', {})
return self.parse_order(data, market)
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://developer.woox.io/api-reference/endpoint/trading/get_orders
https://developer.woox.io/api-reference/endpoint/trading/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 trigger/algo order
:param boolean [params.isTriggered]: 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
:returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
"""
self.load_markets()
paginate = False
paginate, params = self.handle_option_and_params(params, 'fetchOrders', 'paginate')
if paginate:
return self.fetch_paginated_call_incremental('fetchOrders', symbol, since, limit, params, 'page', 500)
request: dict = {}
market: Market = None
trigger = self.safe_bool_2(params, 'stop', 'trigger')
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['startTime'] = since
until = self.safe_integer(params, 'until') # unified in milliseconds
params = self.omit(params, ['until'])
if until is not None:
request['endTime'] = until
if limit is not None:
request['size'] = min(limit, 500)
response = None
if trigger:
response = self.v3PrivateGetTradeAlgoOrders(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "algoOrderId": 10399260,
# "clientAlgoOrderId": 0,
# "rootAlgoOrderId": 10399260,
# "parentAlgoOrderId": 0,
# "symbol": "SPOT_LTC_USDT",
# "algoOrderTag": "default",
# "algoType": "TAKE_PROFIT",
# "side": "BUY",
# "quantity": 0.1,
# "isTriggered": False,
# "triggerPrice": 65,
# "triggerStatus": "USELESS",
# "type": "LIMIT",
# "rootAlgoStatus": "NEW",
# "algoStatus": "NEW",
# "triggerPriceType": "MARKET_PRICE",
# "price": 60,
# "triggerTime": "0",
# "totalExecutedQuantity": 0,
# "visibleQuantity": 0.1,
# "averageExecutedPrice": 0,
# "totalFee": 0,
# "feeAsset": "",
# "totalRebate": 0,
# "rebateAsset": "",
# "reduceOnly": False,
# "createdTime": "1752049747.730",
# "updatedTime": "1752049747.730",
# "positionSide": "BOTH"
# }
# ],
# "meta": {
# "total": 7,
# "recordsPerPage": 1,
# "currentPage": 1
# }
# },
# "timestamp": 1752053127448
# }
#
else:
response = self.v3PrivateGetTradeOrders(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "orderId": 60780315704,
# "clientOrderId": 0,
# "symbol": "SPOT_LTC_USDT",
# "orderTag": "default",
# "side": "BUY",
# "quantity": 0.1,
# "amount": null,
# "type": "LIMIT",
# "status": "NEW",
# "price": 60,
# "executed": 0,
# "visible": 0.1,
# "averageExecutedPrice": 0,
# "totalFee": 0,
# "feeAsset": "LTC",
# "totalRebate": 0,
# "rebateAsset": "USDT",
# "reduceOnly": False,
# "createdTime": "1752049062.496",
# "realizedPnl": null,
# "positionSide": "BOTH",
# "bidAskLevel": null
# }
# ],
# "meta": {
# "total": 11,
# "recordsPerPage": 1,
# "currentPage": 1
# }
# },
# "timestamp": 1752053061236
# }
#
data = self.safe_value(response, 'data', {})
orders = self.safe_list(data, 'rows', [])
return self.parse_orders(orders, market, since, limit)
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://developer.woox.io/api-reference/endpoint/trading/get_orders
https://developer.woox.io/api-reference/endpoint/trading/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 trigger/algo order
:param boolean [params.isTriggered]: whether the order has been triggered(False by default)
:param str [params.side]: 'buy' or 'sell'
:param boolean [params.trailing]: set to True if you want to fetch trailing orders
: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>`
"""
self.load_markets()
extendedParams = self.extend(params, {'status': 'INCOMPLETE'})
return self.fetch_orders(symbol, since, limit, extendedParams)
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://developer.woox.io/api-reference/endpoint/trading/get_orders
https://developer.woox.io/api-reference/endpoint/trading/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 trigger/algo order
:param boolean [params.isTriggered]: whether the order has been triggered(False by default)
:param str [params.side]: 'buy' or 'sell'
:param boolean [params.trailing]: set to True if you want to fetch trailing orders
: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>`
"""
self.load_markets()
extendedParams = self.extend(params, {'status': 'COMPLETED'})
return self.fetch_orders(symbol, since, limit, extendedParams)
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(self, order: dict, market: Market = None) -> Order:
#
# createOrder
# {
# "orderId": 60667653330,
# "clientOrderId": 0,
# "type": "LIMIT",
# "price": 60,
# "quantity": 0.1,
# "amount": null,
# "bidAskLevel": null,
# "timestamp": 1751871779855
# }
#
# createOrder - algo
# {
# "orderId": "1578938",
# "clientOrderId": "0",
# "algoType": "STOP_LOSS",
# "quantity": "0.1",
# "timestamp": "1686149372216"
# }
#
# fetchOrder
# {
# "orderId": 60780315704,
# "clientOrderId": 0,
# "symbol": "SPOT_LTC_USDT",
# "orderTag": "default",
# "side": "BUY",
# "quantity": 0.1,
# "amount": null,
# "type": "LIMIT",
# "status": "NEW",
# "price": 60,
# "executed": 0,
# "visible": 0.1,
# "averageExecutedPrice": 0,
# "totalFee": 0,
# "feeAsset": "LTC",
# "totalRebate": 0,
# "rebateAsset": "USDT",
# "reduceOnly": False,
# "createdTime": "1752049062.496",
# "realizedPnl": null,
# "positionSide": "BOTH",
# "bidAskLevel": null
# }
#
# fetchOrder - algo
# {
# "algoOrderId": 10399260,
# "clientAlgoOrderId": 0,
# "rootAlgoOrderId": 10399260,
# "parentAlgoOrderId": 0,
# "symbol": "SPOT_LTC_USDT",
# "algoOrderTag": "default",
# "algoType": "TAKE_PROFIT",
# "side": "BUY",
# "quantity": 0.1,
# "isTriggered": False,
# "triggerPrice": 65,
# "triggerStatus": "USELESS",
# "type": "LIMIT",
# "rootAlgoStatus": "NEW",
# "algoStatus": "NEW",
# "triggerPriceType": "MARKET_PRICE",
# "price": 60,
# "triggerTime": "0",
# "totalExecutedQuantity": 0,
# "visibleQuantity": 0.1,
# "averageExecutedPrice": 0,
# "totalFee": 0,
# "feeAsset": "",
# "totalRebate": 0,
# "rebateAsset": "",
# "reduceOnly": False,
# "createdTime": "1752049747.732",
# "updatedTime": "1752049747.732",
# "positionSide": "BOTH"
# }
#
timestamp = None
timestrampString = self.safe_string(order, 'createdTime')
if timestrampString is not None:
if timestrampString.find('.') >= 0:
timestamp = self.safe_timestamp(order, 'createdTime') # algo orders
else:
timestamp = self.safe_integer(order, 'createdTime') # regular orders
if timestamp is None:
timestamp = self.safe_integer(order, 'timestamp')
orderId = self.safe_string_2(order, 'orderId', 'algoOrderId')
clientOrderId = self.omit_zero(self.safe_string_2(order, 'clientOrderId', 'clientAlgoOrderId')) # 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(order, 'price')
amount = self.safe_string(order, 'quantity') # This is base amount
cost = self.safe_string(order, 'amount') # This is quote amount
orderType = self.safe_string_lower(order, 'type')
status = self.safe_value_2(order, 'status', 'algoStatus')
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(order, 'averageExecutedPrice'))
# remaining = Precise.string_sub(cost, filled)
fee = self.safe_number(order, 'totalFee')
feeCurrency = self.safe_string(order, 'feeAsset')
triggerPrice = self.safe_number(order, 'triggerPrice')
lastUpdateTimestampString = self.safe_string(order, 'updatedTime')
lastUpdateTimestamp = None
if lastUpdateTimestampString is not None:
if lastUpdateTimestampString.find('.') >= 0:
lastUpdateTimestamp = self.safe_timestamp(order, 'updatedTime') # algo orders
else:
lastUpdateTimestamp = self.safe_integer(order, 'updatedTime') # regular orders
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': orderType,
'timeInForce': self.parse_time_in_force(orderType),
'postOnly': None, # TO_DO
'reduceOnly': self.safe_bool(order, 'reduceOnly'),
'side': side,
'price': price,
'triggerPrice': triggerPrice,
'takeProfitPrice': None,
'stopLossPrice': None,
'average': average,
'amount': amount,
'filled': filled,
'remaining': None, # TO_DO
'cost': cost,
'trades': None,
'fee': {
'cost': fee,
'currency': feeCurrency,
},
'info': order,
}, market)
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 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://developer.woox.io/api-reference/endpoint/public_data/orderbook
: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
"""
self.load_markets()
market = self.market(symbol)
request: dict = {
'symbol': market['id'],
}
if limit is not None:
request['maxLevel'] = limit
response = self.v3PublicGetOrderbook(self.extend(request, params))
#
# }
# {
# "success": True,
# "timestamp": 1751620923344,
# "data": {
# "asks": [
# {
# "price": "108924.86",
# "quantity": "0.032126"
# }
# ],
# "bids": [
# {
# "price": "108924.85",
# "quantity": "1.714147"
# }
# ]
# }
# }
#
data = self.safe_dict(response, 'data', {})
timestamp = self.safe_integer(response, 'timestamp')
return self.parse_order_book(data, symbol, timestamp, 'bids', 'asks', 'price', 'quantity')
def fetch_ohlcv(self, symbol: str, timeframe: str = '1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
"""
https://developer.woox.io/api-reference/endpoint/public_data/klineHistory
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
:param int [params.until]: the latest time in ms to fetch entries for
:returns int[][]: A list of candles ordered, open, high, low, close, volume
"""
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)
if since is not None:
request['after'] = since
until = self.safe_integer(params, 'until')
params = self.omit(params, 'until')
if until is not None:
request['before'] = until
response = self.v3PublicGetKlineHistory(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "symbol": "SPOT_BTC_USDT",
# "open": "108994.16",
# "close": "108994.16",
# "high": "108994.16",
# "low": "108994.16",
# "volume": "0",
# "amount": "0",
# "type": "1m",
# "startTimestamp": 1751622120000,
# "endTimestamp": 1751622180000
# }
# ]
# },
# "timestamp": 1751622205410
# }
#
data = self.safe_dict(response, 'data', {})
rows = self.safe_list(data, 'rows', [])
return self.parse_ohlcvs(rows, market, timeframe, since, limit)
def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
return [
self.safe_integer(ohlcv, 'startTimestamp'),
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'),
]
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://docs.woox.io/#get-trades
: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>`
"""
self.load_markets()
market: Market = None
if symbol is not None:
market = self.market(symbol)
request: dict = {
'oid': id,
}
response = self.v1PrivateGetOrderOidTrades(self.extend(request, params))
# {
# "success": True,
# "rows": [
# {
# "id": "99111647",
# "symbol": "SPOT_WOO_USDT",
# "fee": "0.0024",
# "side": "BUY",
# "executed_timestamp": "1641482113.084",
# "order_id": "87541111",
# "order_tag": "default",
# "executed_price": "1",
# "executed_quantity": "12",
# "fee_asset": "WOO",
# "is_maker": "1"
# }
# ]
# }
trades = self.safe_list(response, 'rows', [])
return self.parse_trades(trades, market, since, limit, params)
def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
"""
fetch all trades made by the user
https://developer.woox.io/api-reference/endpoint/trading/get_transactions
: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
:returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
"""
self.load_markets()
paginate = False
paginate, params = self.handle_option_and_params(params, 'fetchMyTrades', 'paginate')
if paginate:
return 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['startTime'] = since
until = self.safe_integer(params, 'until') # unified in milliseconds
params = self.omit(params, ['until'])
if until is not None:
request['endTime'] = until
if limit is not None:
request['limit'] = limit
response = self.v3PrivateGetTradeTransactionHistory(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "id": 1734947821,
# "symbol": "SPOT_LTC_USDT",
# "orderId": 60780383217,
# "executedPrice": 87.86,
# "executedQuantity": 0.1,
# "fee": 0.0001,
# "realizedPnl": null,
# "feeAsset": "LTC",
# "orderTag": "default",
# "side": "BUY",
# "executedTimestamp": "1752055173.630",
# "isMaker": 0
# }
# ],
# "meta": {
# "total": 1,
# "recordsPerPage": 100,
# "currentPage": 1
# }
# },
# "timestamp": 1752055545121
# }
#
data = self.safe_dict(response, 'data', {})
trades = self.safe_list(data, 'rows', [])
return self.parse_trades(trades, market, since, limit, params)
def fetch_accounts(self, params={}) -> List[Account]:
"""
fetch all the accounts associated with a profile
https://developer.woox.io/api-reference/endpoint/account/get_account_info
https://developer.woox.io/api-reference/endpoint/account/sub_accounts
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a dictionary of `account structures <https://docs.ccxt.com/#/?id=account-structure>` indexed by the account type
"""
mainAccountPromise = self.v3PrivateGetAccountInfo(params)
#
# {
# "success": True,
# "data": {
# "applicationId": "251bf5c4-f3c8-4544-bb8b-80001007c3c0",
# "account": "carlos_jose_lima@yahoo.com",
# "alias": "carlos_jose_lima@yahoo.com",
# "otpauth": True,
# "accountMode": "FUTURES",
# "positionMode": "ONE_WAY",
# "leverage": 0,
# "marginRatio": "10",
# "openMarginRatio": "10",
# "initialMarginRatio": "10",
# "maintenanceMarginRatio": "0.03",
# "totalCollateral": "165.55629469",
# "freeCollateral": "165.55629469",
# "totalAccountValue": "167.32418611",
# "totalTradingValue": "167.32418611",
# "totalVaultValue": "0",
# "totalStakingValue": "0",
# "totalLaunchpadValue": "0",
# "totalEarnValue": "0",
# "referrerID": null,
# "accountType": "Main"
# },
# "timestamp": 1752062807915
# }
#
subAccountPromise = self.v3PrivateGetAccountSubAccountsAll(params)
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "applicationId": "6b43de5c-0955-4887-9862-d84e4689f9fe",
# "name": "sub_account_2",
# "createdTime": "1606897264.994"
# },
# ]
# },
# "timestamp": 1721295317627
# }
#
mainAccountResponse, subAccountResponse = [mainAccountPromise, subAccountPromise]
mainData = self.safe_dict(mainAccountResponse, 'data', {})
mainRows = [mainData]
subData = self.safe_dict(subAccountResponse, 'data', {})
subRows = self.safe_list(subData, 'rows', [])
rows = self.array_concat(mainRows, subRows)
return self.parse_accounts(rows, params)
def parse_account(self, account):
#
# {
# "applicationId": "251bf5c4-f3c8-4544-bb8b-80001007c3c0",
# "account": "carlos_jose_lima@yahoo.com",
# "alias": "carlos_jose_lima@yahoo.com",
# "otpauth": True,
# "accountMode": "FUTURES",
# "positionMode": "ONE_WAY",
# "leverage": 0,
# "marginRatio": "10",
# "openMarginRatio": "10",
# "initialMarginRatio": "10",
# "maintenanceMarginRatio": "0.03",
# "totalCollateral": "165.55629469",
# "freeCollateral": "165.55629469",
# "totalAccountValue": "167.32418611",
# "totalTradingValue": "167.32418611",
# "totalVaultValue": "0",
# "totalStakingValue": "0",
# "totalLaunchpadValue": "0",
# "totalEarnValue": "0",
# "referrerID": null,
# "accountType": "Main"
# }
#
# {
# "applicationId": "6b43de5c-0955-4887-9862-d84e4689f9fe",
# "name": "sub_account_2",
# "createdTime": "1606897264.994"
# }
#
return {
'info': account,
'id': self.safe_string(account, 'applicationId'),
'name': self.safe_string_n(account, ['name', 'account', 'alias']),
'code': None,
'type': self.safe_string_lower(account, 'accountType', 'subaccount'),
}
def fetch_balance(self, params={}) -> Balances:
"""
query for balance and get the amount of funds available for trading or funds locked in orders
https://docs.woox.io/#get-current-holding-get-balance-new
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
"""
self.load_markets()
response = self.v3PrivateGetAssetBalances(params)
#
# {
# "success": True,
# "data": {
# "holding": [
# {
# "token": "0_token",
# "holding": 1,
# "frozen": 0,
# "staked": 0,
# "unbonding": 0,
# "vault": 0,
# "interest": 0,
# "pendingShortQty": 0,
# "pendingLongQty": 0,
# "availableBalance": 0,
# "updatedTime": 312321.121
# }
# ]
# },
# "timestamp": 1673323746259
# }
#
data = self.safe_dict(response, 'data')
return self.parse_balance(data)
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['free'] = self.safe_string(balance, 'availableBalance')
result[code] = account
return self.safe_balance(result)
def fetch_deposit_address(self, code: str, params={}) -> DepositAddress:
"""
fetch the deposit address for a currency associated with self account
https://developer.woox.io/api-reference/endpoint/assets/get_wallet_deposit
:param str code: unified currency code
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
"""
# self method is TODO because of networks unification
self.load_markets()
currency = self.currency(code)
networkCode = None
networkCode, params = self.handle_network_code_and_params(params)
request: dict = {
'token': currency['id'],
'network': self.network_code_to_id(networkCode),
}
response = self.v3PrivateGetAssetWalletDeposit(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "address": "0x31d64B3230f8baDD91dE1710A65DF536aF8f7cDa",
# "extra": ""
# },
# "timestamp": 1721300689532
# }
#
data = self.safe_dict(response, 'data', {})
return self.parse_deposit_address(data, currency)
def get_dedicated_network_id(self, currency, params: dict) -> Any:
networkCode = None
networkCode, params = self.handle_network_code_and_params(params)
networkCode = self.network_id_to_code(networkCode, currency['code'])
networkEntry = self.safe_dict(currency['networks'], networkCode)
if networkEntry is None:
supportedNetworks = list(currency['networks'].keys())
raise BadRequest(self.id + ' can not determine a network code, please provide unified "network" param, one from the following: ' + self.json(supportedNetworks))
currentyNetworkId = self.safe_string(networkEntry, 'currencyNetworkId')
return [currentyNetworkId, params]
def parse_deposit_address(self, depositEntry, currency: Currency = None) -> DepositAddress:
address = self.safe_string(depositEntry, 'address')
self.check_address(address)
return {
'info': depositEntry,
'currency': self.safe_string(currency, 'code'),
'network': None,
'address': address,
'tag': self.safe_string(depositEntry, 'extra'),
}
def get_asset_history_rows(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> Any:
self.load_markets()
request: dict = {}
currency: Currency = None
if code is not None:
currency = self.currency(code)
request['token'] = currency['id']
networkCode = None
networkCode, params = self.handle_network_code_and_params(params)
if networkCode is not None:
request['network'] = self.network_code_to_id(networkCode)
if since is not None:
request['startTime'] = since
if limit is not None:
request['size'] = min(limit, 1000)
transactionType = self.safe_string(params, 'type')
params = self.omit(params, 'type')
if transactionType is not None:
request['type'] = transactionType
response = self.v3PrivateGetAssetWalletHistory(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "createdTime": "1734964440.523",
# "updatedTime": "1734964614.081",
# "id": "24122314340000585",
# "externalId": "241223143600621",
# "applicationId": "251bf5c4-f3c8-4544-bb8b-80001007c3c0",
# "token": "ARB_USDCNATIVE",
# "targetAddress": "0x4d6802d2736daa85e6242ef0dc0f00aa0e68f635",
# "sourceAddress": "0x63DFE4e34A3bFC00eB0220786238a7C6cEF8Ffc4",
# "extra": "",
# "type": "BALANCE",
# "tokenSide": "WITHDRAW",
# "amount": "10.00000000",
# "txId": "0x891ade0a47fd55466bb9d06702bea4edcb75ed9367d9afbc47b93a84f496d2e6",
# "feeToken": "USDC",
# "feeAmount": "2",
# "status": "COMPLETED",
# "confirmingThreshold": null,
# "confirmedNumber": null
# }
# ],
# "meta": {
# "total": 1,
# "records_per_page": 25,
# "current_page": 1
# }
# },
# "timestamp": 1752485344719
# }
#
data = self.safe_dict(response, 'data', {})
return [currency, self.safe_list(data, 'rows', [])]
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 balance of the user
https://developer.woox.io/api-reference/endpoint/assets/get_wallet_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 = 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_ledger_entry(self, item: dict, currency: Currency = None) -> LedgerEntry:
#
# {
# "createdTime": "1734964440.523",
# "updatedTime": "1734964614.081",
# "id": "24122314340000585",
# "externalId": "241223143600621",
# "applicationId": "251bf5c4-f3c8-4544-bb8b-80001007c3c0",
# "token": "ARB_USDCNATIVE",
# "targetAddress": "0x4d6802d2736daa85e6242ef0dc0f00aa0e68f635",
# "sourceAddress": "0x63DFE4e34A3bFC00eB0220786238a7C6cEF8Ffc4",
# "extra": "",
# "type": "BALANCE",
# "tokenSide": "WITHDRAW",
# "amount": "10.00000000",
# "txId": "0x891ade0a47fd55466bb9d06702bea4edcb75ed9367d9afbc47b93a84f496d2e6",
# "feeToken": "USDC",
# "feeAmount": "2",
# "status": "COMPLETED",
# "confirmingThreshold": null,
# "confirmedNumber": null
# }
#
networkizedCode = self.safe_string(item, 'token')
code = self.safe_currency_code(networkizedCode, currency)
currency = self.safe_currency(code, currency)
amount = self.safe_number(item, 'amount')
side = self.safe_string(item, 'tokenSide')
direction = 'in' if (side == 'DEPOSIT') else 'out'
timestamp = self.safe_timestamp(item, 'createdTime')
fee = self.parse_token_and_fee_temp(item, ['feeToken'], ['feeAmount'])
return self.safe_ledger_entry({
'info': item,
'id': self.safe_string(item, 'id'),
'currency': code,
'account': self.safe_string(item, 'account'),
'referenceAccount': None,
'referenceId': self.safe_string(item, 'txId'),
'status': self.parse_transaction_status(self.safe_string(item, 'status')),
'amount': amount,
'before': None,
'after': None,
'direction': direction,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'type': self.parse_ledger_entry_type(self.safe_string(item, 'type')),
'fee': fee,
}, 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)
def get_currency_from_chaincode(self, networkizedCode, currency):
if currency is not None:
return currency
else:
parts = networkizedCode.split('_')
partsLength = len(parts)
firstPart = self.safe_string(parts, 0)
currencyId = self.safe_string(parts, 1, firstPart)
if partsLength > 2:
currencyId += '_' + self.safe_string(parts, 2)
currency = self.safe_currency(currencyId)
return currency
def fetch_deposits(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
"""
fetch all deposits made to an account
https://developer.woox.io/api-reference/endpoint/assets/get_wallet_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 = {
'tokenSide': 'DEPOSIT',
}
return self.fetch_deposits_withdrawals(code, since, limit, self.extend(request, params))
def fetch_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
"""
fetch all withdrawals made from an account
https://developer.woox.io/api-reference/endpoint/assets/get_wallet_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 = {
'tokenSide': 'WITHDRAW',
}
return self.fetch_deposits_withdrawals(code, since, limit, self.extend(request, params))
def fetch_deposits_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
"""
fetch history of deposits and withdrawals
https://developer.woox.io/api-reference/endpoint/assets/get_wallet_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 = {
'type': 'BALANCE',
}
currencyRows = self.get_asset_history_rows(code, since, limit, self.extend(request, params))
currency = self.safe_value(currencyRows, 0)
rows = self.safe_list(currencyRows, 1)
return self.parse_transactions(rows, currency, since, limit, params)
def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
#
# {
# "createdTime": "1734964440.523",
# "updatedTime": "1734964614.081",
# "id": "24122314340000585",
# "externalId": "241223143600621",
# "applicationId": "251bf5c4-f3c8-4544-bb8b-80001007c3c0",
# "token": "ARB_USDCNATIVE",
# "targetAddress": "0x4d6802d2736daa85e6242ef0dc0f00aa0e68f635",
# "sourceAddress": "0x63DFE4e34A3bFC00eB0220786238a7C6cEF8Ffc4",
# "extra": "",
# "type": "BALANCE",
# "tokenSide": "WITHDRAW",
# "amount": "10.00000000",
# "txId": "0x891ade0a47fd55466bb9d06702bea4edcb75ed9367d9afbc47b93a84f496d2e6",
# "feeToken": "USDC",
# "feeAmount": "2",
# "status": "COMPLETED",
# "confirmingThreshold": null,
# "confirmedNumber": null
# }
#
networkizedCode = self.safe_string(transaction, 'token')
currencyDefined = self.get_currency_from_chaincode(networkizedCode, currency)
code = currencyDefined['code']
movementDirection = self.safe_string_lower_n(transaction, ['token_side', 'tokenSide', 'type'])
if movementDirection == 'withdraw':
movementDirection = 'withdrawal'
fee = self.parse_token_and_fee_temp(transaction, ['fee_token', 'feeToken'], ['fee_amount', 'feeAmount'])
addressTo = self.safe_string_n(transaction, ['target_address', 'targetAddress', 'addressTo'])
addressFrom = self.safe_string_2(transaction, 'source_address', 'sourceAddress')
timestamp = self.safe_timestamp_n(transaction, ['created_time', 'createdTime'], self.safe_integer(transaction, 'timestamp'))
return {
'info': transaction,
'id': self.safe_string_n(transaction, ['id', 'withdraw_id', 'withdrawId']),
'txid': self.safe_string_2(transaction, 'tx_id', 'txId'),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'address': None,
'addressFrom': addressFrom,
'addressTo': addressTo,
'tag': self.safe_string_2(transaction, 'extra', 'tag'),
'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_timestamp_2(transaction, 'updated_time', 'updatedTime'),
'comment': None,
'internal': None,
'fee': fee,
'network': self.network_id_to_code(self.safe_string(transaction, 'network')),
}
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)
def transfer(self, code: str, amount: float, fromAccount: str, toAccount: str, params={}) -> TransferEntry:
"""
transfer currency internally between wallets on the same account
https://docs.woox.io/#get-transfer-history
:param str code: unified currency code
:param float amount: amount to transfer
:param str fromAccount: account to transfer from
:param str toAccount: account to transfer to
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
"""
self.load_markets()
currency = self.currency(code)
request: dict = {
'token': currency['id'],
'amount': self.parse_to_numeric(amount),
'from': {
'applicationId': fromAccount,
},
'to': {
'applicationId': toAccount,
},
}
response = self.v3PrivatePostAssetTransfer(self.extend(request, params))
#
# {
# "success": True,
# "id": 200
# }
#
data = self.safe_dict(response, 'data', {})
data['timestamp'] = self.safe_integer(response, 'timestamp')
data['token'] = currency['id']
data['status'] = 'ok'
transfer = self.parse_transfer(data, currency)
transferOptions = self.safe_dict(self.options, 'transfer', {})
fillResponseFromRequest = self.safe_bool(transferOptions, 'fillResponseFromRequest', True)
if fillResponseFromRequest:
transfer['amount'] = amount
transfer['fromAccount'] = fromAccount
transfer['toAccount'] = toAccount
return transfer
def fetch_transfers(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[TransferEntry]:
"""
fetch a history of internal transfers made on an account
https://developer.woox.io/api-reference/endpoint/assets/get_transfer_history
:param str code: unified currency code of the currency transferred
:param int [since]: the earliest time in ms to fetch transfers for
:param int [limit]: the maximum number of transfers structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:param int [params.until]: the latest time in ms to fetch entries for
:returns dict[]: a list of `transfer structures <https://docs.ccxt.com/#/?id=transfer-structure>`
"""
request: dict = {}
currency = None
if code is not None:
currency = self.currency(code)
if limit is not None:
request['size'] = limit
if since is not None:
request['startTime'] = since
until = self.safe_integer(params, 'until') # unified in milliseconds
params = self.omit(params, ['until'])
if until is not None:
request['endTime'] = until
response = self.v3PrivateGetAssetTransferHistory(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "id": 225,
# "token": "USDT",
# "amount": "1000000",
# "status": "COMPLETED",
# "from": {
# "applicationId": "046b5c5c-5b44-4d27-9593-ddc32c0a08ae",
# "accountName": "Main"
# },
# "to": {
# "applicationId": "082ae5ae-e26a-4fb1-be5b-03e5b4867663",
# "accountName": "sub001"
# },
# "createdTime": "1642660941.534",
# "updatedTime": "1642660941.950"
# }
# ],
# "meta": {
# "total": 46,
# "recordsPerPage": 1,
# "currentPage": 1
# }
# },
# "timestamp": 1721295317627
# }
#
data = self.safe_dict(response, 'data', {})
rows = self.safe_list(data, 'rows', [])
return self.parse_transfers(rows, currency, since, limit, params)
def parse_transfer(self, transfer: dict, currency: Currency = None) -> TransferEntry:
#
# fetchTransfers
# {
# "id": 46704,
# "token": "USDT",
# "amount": 30000.00000000,
# "status": "COMPLETED",
# "from_application_id": "0f1bd3cd-dba2-4563-b8bb-0adb1bfb83a3",
# "to_application_id": "c01e6940-a735-4022-9b6c-9d3971cdfdfa",
# "from_user": "LeverageLow",
# "to_user": "dev",
# "created_time": "1709022325.427",
# "updated_time": "1709022325.542"
# }
# {
# "id": 225,
# "token": "USDT",
# "amount": "1000000",
# "status": "COMPLETED",
# "from": {
# "applicationId": "046b5c5c-5b44-4d27-9593-ddc32c0a08ae",
# "accountName": "Main"
# },
# "to": {
# "applicationId": "082ae5ae-e26a-4fb1-be5b-03e5b4867663",
# "accountName": "sub001"
# },
# "createdTime": "1642660941.534",
# "updatedTime": "1642660941.950"
# }
#
# transfer
# {
# "success": True,
# "id": 200
# }
#
code = self.safe_currency_code(self.safe_string(transfer, 'token'), currency)
timestamp = self.safe_timestamp_2(transfer, 'createdTime', 'timestamp')
success = self.safe_bool(transfer, 'success')
status: Str = None
if success is not None:
status = 'ok' if success else 'failed'
fromAccount = self.safe_dict(transfer, 'from', {})
toAccount = self.safe_dict(transfer, 'to', {})
return {
'id': self.safe_string(transfer, 'id'),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'currency': code,
'amount': self.safe_number(transfer, 'amount'),
'fromAccount': self.safe_string(fromAccount, 'applicationId'),
'toAccount': self.safe_string(toAccount, 'applicationId'),
'status': self.parse_transfer_status(self.safe_string(transfer, 'status', status)),
'info': transfer,
}
def parse_transfer_status(self, status: Str) -> Str:
statuses: dict = {
'NEW': 'pending',
'CONFIRMING': 'pending',
'PROCESSING': 'pending',
'COMPLETED': 'ok',
'CANCELED': 'canceled',
}
return self.safe_string(statuses, status, status)
def withdraw(self, code: str, amount: float, address: str, tag: Str = None, params={}) -> Transaction:
"""
make a withdrawal
https://docs.woox.io/#token-withdraw-v3
: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>`
"""
tag, params = self.handle_withdraw_tag_and_params(tag, params)
self.load_markets()
self.check_address(address)
currency = self.currency(code)
request: dict = {
'amount': amount,
'address': address,
}
if tag is not None:
request['extra'] = tag
network = self.safe_string(params, 'network')
if network is None:
raise ArgumentsRequired(self.id + ' withdraw() requires a network parameter for ' + code)
params = self.omit(params, 'network')
request['token'] = currency['id']
request['network'] = self.network_code_to_id(network)
response = self.v3PrivatePostAssetWalletWithdraw(self.extend(request, params))
#
# {
# "success": True,
# "withdraw_id": "20200119145703654"
# }
#
data = self.safe_dict(response, 'data', {})
transactionData = self.extend(data, {
'id': self.safe_string(data, 'withdrawId'),
'timestamp': self.safe_integer(response, 'timestamp'),
'currency': code,
'amount': amount,
'addressTo': address,
'tag': tag,
'network': network,
'type': 'withdrawal',
'status': 'pending',
})
return self.parse_transaction(transactionData, currency)
def repay_margin(self, code: str, amount: float, symbol: Str = None, params={}):
"""
repay borrowed margin and interest
https://docs.woox.io/#repay-interest
:param str code: unified currency code of the currency to repay
:param float amount: the amount to repay
:param str symbol: not used by woo.repayMargin()
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `margin loan structure <https://docs.ccxt.com/#/?id=margin-loan-structure>`
"""
self.load_markets()
market: Market = None
if symbol is not None:
market = self.market(symbol)
symbol = market['symbol']
currency = self.currency(code)
request: dict = {
'token': currency['id'], # interest token that you want to repay
'amount': self.currency_to_precision(code, amount),
}
response = self.v1PrivatePostInterestRepay(self.extend(request, params))
#
# {
# "success": True,
# }
#
transaction = self.parse_margin_loan(response, currency)
return self.extend(transaction, {
'amount': amount,
'symbol': symbol,
})
def parse_margin_loan(self, info, currency: Currency = None):
#
# {
# "success": True,
# }
#
return {
'id': None,
'currency': self.safe_currency_code(None, currency),
'amount': None,
'symbol': None,
'timestamp': None,
'datetime': None,
'info': info,
}
def nonce(self):
return self.milliseconds() - self.options['timeDifference']
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 += access + '/' + pathWithParams
if params:
url += '?' + self.urlencode(params)
elif access == 'pub':
url += pathWithParams
if params:
url += '?' + self.urlencode(params)
else:
self.check_required_credentials()
if method == 'POST' and (path == 'trade/algoOrder' or path == 'trade/order'):
isSandboxMode = self.safe_bool(self.options, 'sandboxMode', False)
if not isSandboxMode:
applicationId = 'bc830de7-50f3-460b-9ee0-f430f83f9dad'
brokerId = self.safe_string(self.options, 'brokerId', applicationId)
isTrigger = path.find('algo') > -1
if isTrigger:
params['brokerId'] = brokerId
else:
params['broker_id'] = brokerId
params = self.keysort(params)
auth = ''
ts = str(self.nonce())
url += pathWithParams
headers = {
'x-api-key': self.apiKey,
'x-api-timestamp': ts,
}
if version == 'v3':
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:
query = self.urlencode(params)
url += '?' + query
auth += '?' + query
else:
auth = self.urlencode(params)
if method == 'POST' or method == 'PUT' or method == 'DELETE':
body = auth
else:
if params:
url += '?' + auth
auth += '|' + ts
headers['content-type'] = 'application/x-www-form-urlencoded'
headers['x-api-signature'] = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256)
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)
return None
def parse_income(self, income, market: Market = None):
#
# {
# "id": 1286360,
# "symbol": "PERP_BTC_USDT",
# "fundingRate": -0.00001445,
# "markPrice": "26930.60000000",
# "fundingFee": "9.56021744",
# "fundingIntervalHours": 8,
# "paymentType": "Pay",
# "status": "COMPLETED",
# "createdTime": 1696060873259,
# "updatedTime": 1696060873286
# }
#
marketId = self.safe_string(income, 'symbol')
symbol = self.safe_symbol(marketId, market)
amount = self.safe_string(income, 'fundingFee')
code = self.safe_currency_code('USD')
id = self.safe_string(income, 'id')
timestamp = self.safe_integer(income, 'updatedTime')
rate = self.safe_number(income, 'fundingRate')
paymentType = self.safe_string(income, 'paymentType')
amount = Precise.string_neg(amount) if (paymentType == 'Pay') else amount
return {
'info': income,
'symbol': symbol,
'code': code,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'id': id,
'amount': self.parse_number(amount),
'rate': rate,
}
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://developer.woox.io/api-reference/endpoint/futures/get_fundingFee_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>`
"""
self.load_markets()
paginate = False
paginate, params = self.handle_option_and_params(params, 'fetchFundingHistory', 'paginate')
if paginate:
return 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['startTime'] = since
until = self.safe_integer(params, 'until') # unified in milliseconds
params = self.omit(params, ['until'])
if until is not None:
request['endTime'] = until
if limit is not None:
request['size'] = min(limit, 500)
response = self.v3PrivateGetFuturesFundingFeeHistory(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "meta": {
# "total": 670,
# "recordsPerPage": 25,
# "currentPage": 1
# },
# "rows": [
# {
# "id": 1286360,
# "symbol": "PERP_BTC_USDT",
# "fundingRate": -0.00001445,
# "markPrice": "26930.60000000",
# "fundingFee": "9.56021744",
# "fundingIntervalHours": 8,
# "paymentType": "Pay",
# "status": "COMPLETED",
# "createdTime": 1696060873259,
# "updatedTime": 1696060873286
# }
# ]
# },
# "timestamp": 1721351502594
# }
#
data = self.safe_dict(response, 'data', {})
rows = self.safe_list(data, 'rows', [])
return self.parse_incomes(rows, market, since, limit)
def parse_funding_rate(self, fundingRate, market: Market = None) -> FundingRate:
#
# {
# "symbol": "PERP_BTC_USDT",
# "estFundingRate": "-0.00000441",
# "estFundingRateTimestamp": 1751623979022,
# "lastFundingRate": "-0.00004953",
# "lastFundingRateTimestamp": 1751616000000,
# "nextFundingTime": 1751644800000,
# "lastFundingIntervalHours": 8,
# "estFundingIntervalHours": 8
# }
#
symbol = self.safe_string(fundingRate, 'symbol')
market = self.market(symbol)
nextFundingTimestamp = self.safe_integer(fundingRate, 'nextFundingTime')
estFundingRateTimestamp = self.safe_integer(fundingRate, 'estFundingRateTimestamp')
lastFundingRateTimestamp = self.safe_integer(fundingRate, 'lastFundingRateTimestamp')
intervalString = self.safe_string(fundingRate, 'estFundingIntervalHours')
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, 'estFundingRate'),
'fundingTimestamp': nextFundingTimestamp,
'fundingDatetime': self.iso8601(nextFundingTimestamp),
'nextFundingRate': None,
'nextFundingTimestamp': None,
'nextFundingDatetime': None,
'previousFundingRate': self.safe_number(fundingRate, 'lastFundingRate'),
'previousFundingTimestamp': lastFundingRateTimestamp,
'previousFundingDatetime': self.iso8601(lastFundingRateTimestamp),
'interval': intervalString + 'h',
}
def fetch_funding_interval(self, symbol: str, params={}) -> FundingRate:
"""
fetch the current funding rate interval
https://developer.woox.io/api-reference/endpoint/public_data/fundingRate
: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 self.fetch_funding_rate(symbol, params)
def fetch_funding_rate(self, symbol: str, params={}) -> FundingRate:
"""
fetch the current funding rate
https://developer.woox.io/api-reference/endpoint/public_data/fundingRate
: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>`
"""
self.load_markets()
market = self.market(symbol)
request: dict = {
'symbol': market['id'],
}
response = self.v3PublicGetFundingRate(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "symbol": "PERP_BTC_USDT",
# "estFundingRate": "-0.00000441",
# "estFundingRateTimestamp": 1751623979022,
# "lastFundingRate": "-0.00004953",
# "lastFundingRateTimestamp": 1751616000000,
# "nextFundingTime": 1751644800000,
# "lastFundingIntervalHours": 8,
# "estFundingIntervalHours": 8
# }
# ]
# },
# "timestamp": 1751624037798
# }
#
data = self.safe_dict(response, 'data', {})
rows = self.safe_list(data, 'rows', [])
first = self.safe_dict(rows, 0, {})
return self.parse_funding_rate(first, market)
def fetch_funding_rates(self, symbols: Strings = None, params={}) -> FundingRates:
"""
fetch the funding rate for multiple markets
https://developer.woox.io/api-reference/endpoint/public_data/fundingRate
:param str[]|None symbols: list of unified market symbols
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rates-structure>`, indexed by market symbols
"""
self.load_markets()
symbols = self.market_symbols(symbols)
response = self.v3PublicGetFundingRate(params)
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "symbol": "PERP_BTC_USDT",
# "estFundingRate": "-0.00000441",
# "estFundingRateTimestamp": 1751623979022,
# "lastFundingRate": "-0.00004953",
# "lastFundingRateTimestamp": 1751616000000,
# "nextFundingTime": 1751644800000,
# "lastFundingIntervalHours": 8,
# "estFundingIntervalHours": 8
# }
# ]
# },
# "timestamp": 1751624037798
# }
#
data = self.safe_dict(response, 'data', {})
rows = self.safe_list(data, 'rows', [])
return self.parse_funding_rates(rows, symbols)
def fetch_funding_rate_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
"""
fetches historical funding rate prices
https://developer.woox.io/api-reference/endpoint/public_data/fundingRateHistory
: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>`
"""
self.load_markets()
paginate = False
paginate, params = self.handle_option_and_params(params, 'fetchFundingRateHistory', 'paginate')
if paginate:
return self.fetch_paginated_call_incremental('fetchFundingRateHistory', symbol, since, limit, params, 'page', 25)
if symbol is None:
raise ArgumentsRequired(self.id + ' fetchFundingRateHistory() requires a symbol argument')
market = self.market(symbol)
symbol = market['symbol']
request: dict = {
'symbol': market['id'],
}
if since is not None:
request['startTime'] = since
request, params = self.handle_until_option('endTime', request, params)
response = self.v3PublicGetFundingRateHistory(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "rows": [
# {
# "symbol": "PERP_BTC_USDT",
# "fundingRate": "-0.00004953",
# "fundingRateTimestamp": 1751616000000,
# "nextFundingTime": 1751644800000,
# "markPrice": "108708"
# }
# ],
# "meta": {
# "total": 11690,
# "recordsPerPage": 25,
# "currentPage": 1
# }
# },
# "timestamp": 1751632390031
# }
#
data = self.safe_dict(response, 'data', {})
rows = self.safe_list(data, 'rows', [])
rates = []
for i in range(0, len(rows)):
entry = rows[i]
marketId = self.safe_string(entry, 'symbol')
timestamp = self.safe_integer(entry, 'fundingRateTimestamp')
rates.append({
'info': entry,
'symbol': self.safe_symbol(marketId),
'fundingRate': self.safe_number(entry, 'fundingRate'),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
})
sorted = self.sort_by(rates, 'timestamp')
return self.filter_by_symbol_since_limit(sorted, symbol, since, limit)
def set_position_mode(self, hedged: bool, symbol: Str = None, params={}):
"""
set hedged to True or False for a market
https://developer.woox.io/api-reference/endpoint/futures/position_mode
:param bool hedged: set to True to use HEDGE_MODE, False for ONE_WAY
:param str symbol: not used by woo setPositionMode
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: response from the exchange
"""
hedgeMode = None
if hedged:
hedgeMode = 'HEDGE_MODE'
else:
hedgeMode = 'ONE_WAY'
request: dict = {
'positionMode': hedgeMode,
}
response = self.v3PrivatePutFuturesPositionMode(self.extend(request, params))
#
# {
# "success": True,
# "timestamp": 1752550492845
# }
#
return response
def fetch_leverage(self, symbol: str, params={}) -> Leverage:
"""
fetch the set leverage for a market
https://developer.woox.io/api-reference/endpoint/account/get_account_info
https://developer.woox.io/api-reference/endpoint/futures/get_leverage
:param str symbol: unified market symbol
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.marginMode]: *for swap markets only* 'cross' or 'isolated'
:param str [params.positionMode]: *for swap markets only* 'ONE_WAY' or 'HEDGE_MODE'
:returns dict: a `leverage structure <https://docs.ccxt.com/#/?id=leverage-structure>`
"""
self.load_markets()
market = self.market(symbol)
response: dict = None
if market['spot']:
response = self.v3PrivateGetAccountInfo(params)
#
# {
# "success": True,
# "data": {
# "applicationId": "dsa",
# "account": "dsa",
# "alias": "haha",
# "otpauth": True,
# "accountMode": "FUTURES",
# "positionMode": "ONE_WAY",
# "leverage": 0,
# "marginRatio": "10",
# "openMarginRatio": "10",
# "initialMarginRatio": "10",
# "maintenanceMarginRatio": "0.03",
# "totalCollateral": "165.6115334",
# "freeCollateral": "165.6115334",
# "totalAccountValue": "167.52723093",
# "totalTradingValue": "167.52723093",
# "totalVaultValue": "0",
# "totalStakingValue": "0",
# "totalLaunchpadValue": "0",
# "totalEarnValue": "0",
# "referrerID": null,
# "accountType": "Main"
# },
# "timestamp": 1752645129054
# }
#
elif market['swap']:
request: dict = {
'symbol': market['id'],
}
marginMode: Str = None
marginMode, params = self.handle_margin_mode_and_params('fetchLeverage', params, 'cross')
request['marginMode'] = self.encode_margin_mode(marginMode)
response = self.v3PrivateGetFuturesLeverage(self.extend(request, params))
#
# HEDGE_MODE
# {
# "success": True,
# "data":
# {
# "symbol": "PERP_ETH_USDT",
# "marginMode": "CROSS",
# "positionMode": "HEDGE_MODE",
# "details": [
# {
# "positionSide": "LONG",
# "leverage": 10
# },
# {
# "positionSide": "SHORT",
# "leverage": 10
# }
# ]
# },
# "timestamp": 1720886470482
# }
#
# ONE_WAY
# {
# "success": True,
# "data": {
# "symbol": "PERP_ETH_USDT",
# "marginMode": "ISOLATED",
# "positionMode": "ONE_WAY",
# "details": [
# {
# "positionSide": "BOTH",
# "leverage": 10
# }
# ]
# },
# "timestamp": 1720886810317
# }
#
else:
raise NotSupported(self.id + ' fetchLeverage() is not supported for ' + market['type'] + ' markets')
data = self.safe_dict(response, 'data', {})
return self.parse_leverage(data, market)
def parse_leverage(self, leverage: dict, market: Market = None) -> Leverage:
marketId = self.safe_string(leverage, 'symbol')
market = self.safe_market(marketId, market)
marginMode = self.safe_string_lower(leverage, 'marginMode')
spotLeverage = self.safe_integer(leverage, 'leverage')
if spotLeverage == 0:
spotLeverage = None
longLeverage = spotLeverage
shortLeverage = spotLeverage
details = self.safe_list(leverage, 'details', [])
for i in range(0, len(details)):
position = self.safe_dict(details, i, {})
positionLeverage = self.safe_integer(position, 'leverage')
side = self.safe_string(position, 'positionSide')
if side == 'BOTH':
longLeverage = positionLeverage
shortLeverage = positionLeverage
elif side == 'LONG':
longLeverage = positionLeverage
elif side == 'SHORT':
shortLeverage = positionLeverage
return {
'info': leverage,
'symbol': market['symbol'],
'marginMode': marginMode,
'longLeverage': longLeverage,
'shortLeverage': shortLeverage,
}
def set_leverage(self, leverage: int, symbol: Str = None, params={}):
"""
set the level of leverage for a market
https://developer.woox.io/api-reference/endpoint/spot_margin/set_leverage
https://developer.woox.io/api-reference/endpoint/futures/set_leverage
:param float leverage: the rate of leverage(1, 2, 3, 4 or 5 for spot markets, 1, 2, 3, 4, 5, 10, 15, 20 for swap markets)
:param str [symbol]: unified market symbol(is mandatory for swap markets)
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.marginMode]: *for swap markets only* 'cross' or 'isolated'
:param str [params.positionMode]: *for swap markets only* 'ONE_WAY' or 'HEDGE_MODE'
:returns dict: response from the exchange
"""
self.load_markets()
request: dict = {
'leverage': leverage,
}
market: Market = None
if symbol is not None:
market = self.market(symbol)
if (symbol is None) or market['spot']:
return self.v3PrivatePostSpotMarginLeverage(self.extend(request, params))
elif market['swap']:
request['symbol'] = market['id']
marginMode: Str = None
marginMode, params = self.handle_margin_mode_and_params('fetchLeverage', params, 'cross')
request['marginMode'] = self.encode_margin_mode(marginMode)
return self.v3PrivatePutFuturesLeverage(self.extend(request, params))
else:
raise NotSupported(self.id + ' fetchLeverage() is not supported for ' + market['type'] + ' markets')
def add_margin(self, symbol: str, amount: float, params={}) -> MarginModification:
"""
add margin
https://docs.woox.io/#update-isolated-margin-setting
: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
:param str [params.position_side]: 'LONG' or 'SHORT' in hedge mode, 'BOTH' in one way mode
:returns dict: a `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
"""
return self.modify_margin_helper(symbol, amount, 'ADD', params)
def reduce_margin(self, symbol: str, amount: float, params={}) -> MarginModification:
"""
remove margin from a position
https://docs.woox.io/#update-isolated-margin-setting
: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
:param str [params.position_side]: 'LONG' or 'SHORT' in hedge mode, 'BOTH' in one way mode
:returns dict: a `margin structure <https://docs.ccxt.com/#/?id=reduce-margin-structure>`
"""
return self.modify_margin_helper(symbol, amount, 'REDUCE', params)
def modify_margin_helper(self, symbol: str, amount, type, params={}) -> MarginModification:
self.load_markets()
market = self.market(symbol)
request: dict = {
'symbol': market['id'],
'adjust_token': 'USDT', # todo check
'adjust_amount': amount,
'action': type,
}
return self.v1PrivatePostClientIsolatedMargin(self.extend(request, params))
def fetch_position(self, symbol: Str, params={}):
"""
fetch data on an open position
https://developer.woox.io/api-reference/endpoint/futures/get_positions
: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>`
"""
self.load_markets()
market = self.market(symbol)
request: dict = {
'symbol': market['id'],
}
response = self.v3PrivateGetFuturesPositions(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "positions": [
# {
# "symbol": "PERP_LTC_USDT",
# "holding": "0.1",
# "pendingLongQty": "0",
# "pendingShortQty": "0",
# "settlePrice": "96.87",
# "averageOpenPrice": "96.87",
# "pnl24H": "0",
# "fee24H": "0.0048435",
# "markPrice": "96.83793449",
# "estLiqPrice": "0",
# "timestamp": 1752500555823,
# "adlQuantile": 2,
# "positionSide": "BOTH",
# "marginMode": "CROSS",
# "isolatedMarginToken": "",
# "isolatedMarginAmount": "0",
# "isolatedFrozenLong": "0",
# "isolatedFrozenShort": "0",
# "leverage": 10
# }
# ]
# },
# "timestamp": 1752500579848
# }
#
result = self.safe_dict(response, 'data', {})
positions = self.safe_list(result, 'positions', [])
first = self.safe_dict(positions, 0, {})
return self.parse_position(first, market)
def fetch_positions(self, symbols: Strings = None, params={}) -> List[Position]:
"""
fetch all open positions
https://developer.woox.io/api-reference/endpoint/futures/get_positions
: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>`
"""
self.load_markets()
response = self.v3PrivateGetFuturesPositions(params)
#
# {
# "success": True,
# "data": {
# "positions": [
# {
# "symbol": "PERP_LTC_USDT",
# "holding": "0.1",
# "pendingLongQty": "0",
# "pendingShortQty": "0",
# "settlePrice": "96.87",
# "averageOpenPrice": "96.87",
# "pnl24H": "0",
# "fee24H": "0.0048435",
# "markPrice": "96.83793449",
# "estLiqPrice": "0",
# "timestamp": 1752500555823,
# "adlQuantile": 2,
# "positionSide": "BOTH",
# "marginMode": "CROSS",
# "isolatedMarginToken": "",
# "isolatedMarginAmount": "0",
# "isolatedFrozenLong": "0",
# "isolatedFrozenShort": "0",
# "leverage": 10
# }
# ]
# },
# "timestamp": 1752500579848
# }
#
result = self.safe_dict(response, 'data', {})
positions = self.safe_list(result, 'positions', [])
return self.parse_positions(positions, symbols)
def parse_position(self, position: dict, market: Market = None):
#
# v1PrivateGetPositionSymbol
# {
# "symbol": "PERP_ETH_USDT",
# "position_side": "BOTH",
# "leverage": 10,
# "margin_mode": "CROSS",
# "average_open_price": 3139.9,
# "isolated_margin_amount": 0.0,
# "isolated_margin_token": "",
# "opening_time": "1720627963.094",
# "mark_price": 3155.19169891,
# "pending_short_qty": 0.0,
# "pending_long_qty": 0.0,
# "holding": -0.7,
# "pnl_24_h": 0.0,
# "est_liq_price": 9107.40055552,
# "settle_price": 3151.0319904,
# "success": True,
# "fee_24_h": 0.0,
# "isolated_frozen_long": 0.0,
# "isolated_frozen_short": 0.0,
# "timestamp": "1720867502.544"
# }
#
# v3PrivateGetPositions
# {
# "symbol": "PERP_LTC_USDT",
# "holding": "0.1",
# "pendingLongQty": "0",
# "pendingShortQty": "0",
# "settlePrice": "96.87",
# "averageOpenPrice": "96.87",
# "pnl24H": "0",
# "fee24H": "0.0048435",
# "markPrice": "96.83793449",
# "estLiqPrice": "0",
# "timestamp": 1752500555823,
# "adlQuantile": 2,
# "positionSide": "BOTH",
# "marginMode": "CROSS",
# "isolatedMarginToken": "",
# "isolatedMarginAmount": "0",
# "isolatedFrozenLong": "0",
# "isolatedFrozenShort": "0",
# "leverage": 10
# }
#
contract = self.safe_string(position, 'symbol')
market = self.safe_market(contract, market)
size = self.safe_string(position, 'holding')
side: Str = None
if Precise.string_gt(size, '0'):
side = 'long'
else:
side = 'short'
contractSize = self.safe_string(market, 'contractSize')
markPrice = self.safe_string_2(position, 'markPrice', 'mark_price')
timestampString = self.safe_string(position, 'timestamp')
timestamp = None
if timestampString is not None:
if timestampString.find('.') > -1:
timestamp = self.safe_timestamp(position, 'timestamp')
else:
timestamp = self.safe_integer(position, 'timestamp')
entryPrice = self.safe_string_2(position, 'averageOpenPrice', 'average_open_price')
priceDifference = Precise.string_sub(markPrice, entryPrice)
unrealisedPnl = Precise.string_mul(priceDifference, size)
size = Precise.string_abs(size)
notional = Precise.string_mul(size, markPrice)
positionSide = self.safe_string(position, 'positionSide') # 'SHORT' or 'LONG' for hedged, 'BOTH' for non-hedged
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': self.safe_number(position, 'leverage'),
'unrealizedPnl': self.parse_number(unrealisedPnl),
'contracts': self.parse_number(size),
'contractSize': self.parse_number(contractSize),
'marginRatio': None,
'liquidationPrice': self.safe_number_2(position, 'estLiqPrice', 'est_liq_price'),
'markPrice': self.parse_number(markPrice),
'lastPrice': None,
'collateral': None,
'marginMode': self.safe_string_lower_2(position, 'marginMode', 'margin_mode'),
'side': side,
'percentage': None,
'hedged': positionSide != 'BOTH',
'stopLossPrice': None,
'takeProfitPrice': None,
})
def fetch_convert_quote(self, fromCode: str, toCode: str, amount: Num = None, params={}) -> Conversion:
"""
fetch a quote for converting from one currency to another
https://docs.woox.io/#get-quote-rfq
:param str fromCode: the currency that you want to sell and convert from
:param str toCode: the currency that you want to buy and convert into
:param float [amount]: how much you want to trade in units of the from currency
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
"""
self.load_markets()
request: dict = {
'sellToken': fromCode.upper(),
'buyToken': toCode.upper(),
'sellQuantity': self.number_to_string(amount),
}
response = self.v3PrivateGetConvertRfq(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "quoteId": 123123123,
# "counterPartyId": "",
# "sellToken": "ETH",
# "sellQuantity": "0.0445",
# "buyToken": "USDT",
# "buyQuantity": "33.45",
# "buyPrice": "6.77",
# "expireTimestamp": 1659084466000,
# "message": 1659084466000
# }
# }
#
data = self.safe_dict(response, 'data', {})
fromCurrencyId = self.safe_string(data, 'sellToken', fromCode)
fromCurrency = self.currency(fromCurrencyId)
toCurrencyId = self.safe_string(data, 'buyToken', toCode)
toCurrency = self.currency(toCurrencyId)
return self.parse_conversion(data, fromCurrency, toCurrency)
def create_convert_trade(self, id: str, fromCode: str, toCode: str, amount: Num = None, params={}) -> Conversion:
"""
convert from one currency to another
https://docs.woox.io/#send-quote-rft
:param str id: the id of the trade that you want to make
:param str fromCode: the currency that you want to sell and convert from
:param str toCode: the currency that you want to buy and convert into
:param float [amount]: how much you want to trade in units of the from currency
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
"""
self.load_markets()
request: dict = {
'quoteId': id,
}
response = self.v3PrivatePostConvertRft(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "quoteId": 123123123,
# "counterPartyId": "",
# "rftAccepted": 1 # 1 -> success; 2 -> processing; 3 -> fail
# }
# }
#
data = self.safe_dict(response, 'data', {})
return self.parse_conversion(data)
def fetch_convert_trade(self, id: str, code: Str = None, params={}) -> Conversion:
"""
fetch the data for a conversion trade
https://docs.woox.io/#get-quote-trade
:param str id: the id of the trade that you want to fetch
:param str [code]: the unified currency code of the conversion trade
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
"""
self.load_markets()
request: dict = {
'quoteId': id,
}
response = self.v3PrivateGetConvertTrade(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "quoteId": 12,
# "buyAsset": "",
# "sellAsset": "",
# "buyAmount": 12.11,
# "sellAmount": 12.11,
# "tradeStatus": 12,
# "createdTime": ""
# }
# }
#
data = self.safe_dict(response, 'data', {})
fromCurrencyId = self.safe_string(data, 'sellAsset')
toCurrencyId = self.safe_string(data, 'buyAsset')
fromCurrency = None
toCurrency = None
if fromCurrencyId is not None:
fromCurrency = self.currency(fromCurrencyId)
if toCurrencyId is not None:
toCurrency = self.currency(toCurrencyId)
return self.parse_conversion(data, fromCurrency, toCurrency)
def fetch_convert_trade_history(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Conversion]:
"""
fetch the users history of conversion trades
https://docs.woox.io/#get-quote-trades
:param str [code]: the unified currency code
:param int [since]: the earliest time in ms to fetch conversions for
:param int [limit]: the maximum number of conversion structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:param int [params.until]: timestamp in ms of the latest conversion to fetch
:returns dict[]: a list of `conversion structures <https://docs.ccxt.com/#/?id=conversion-structure>`
"""
self.load_markets()
request: dict = {}
request, params = self.handle_until_option('endTime', request, params)
if since is not None:
request['startTime'] = since
if limit is not None:
request['size'] = limit
response = self.v3PrivateGetConvertTrades(self.extend(request, params))
#
# {
# "success": True,
# "data": {
# "count": 12,
# "tradeVos":[
# {
# "quoteId": 12,
# "buyAsset": "",
# "sellAsset": "",
# "buyAmount": 12.11,
# "sellAmount": 12.11,
# "tradeStatus": 12,
# "createdTime": ""
# }
# ...
# ]
# }
# }
#
data = self.safe_dict(response, 'data', {})
rows = self.safe_list(data, 'tradeVos', [])
return self.parse_conversions(rows, code, 'sellAsset', 'buyAsset', since, limit)
def parse_conversion(self, conversion: dict, fromCurrency: Currency = None, toCurrency: Currency = None) -> Conversion:
#
# fetchConvertQuote
#
# {
# "quoteId": 123123123,
# "counterPartyId": "",
# "sellToken": "ETH",
# "sellQuantity": "0.0445",
# "buyToken": "USDT",
# "buyQuantity": "33.45",
# "buyPrice": "6.77",
# "expireTimestamp": 1659084466000,
# "message": 1659084466000
# }
#
# createConvertTrade
#
# {
# "quoteId": 123123123,
# "counterPartyId": "",
# "rftAccepted": 1 # 1 -> success; 2 -> processing; 3 -> fail
# }
#
# fetchConvertTrade, fetchConvertTradeHistory
#
# {
# "quoteId": 12,
# "buyAsset": "",
# "sellAsset": "",
# "buyAmount": 12.11,
# "sellAmount": 12.11,
# "tradeStatus": 12,
# "createdTime": ""
# }
#
timestamp = self.safe_integer_2(conversion, 'expireTimestamp', 'createdTime')
fromCurr = self.safe_string_2(conversion, 'sellToken', 'buyAsset')
fromCode = self.safe_currency_code(fromCurr, fromCurrency)
to = self.safe_string_2(conversion, 'buyToken', 'sellAsset')
toCode = self.safe_currency_code(to, toCurrency)
return {
'info': conversion,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'id': self.safe_string(conversion, 'quoteId'),
'fromCurrency': fromCode,
'fromAmount': self.safe_number_2(conversion, 'sellQuantity', 'sellAmount'),
'toCurrency': toCode,
'toAmount': self.safe_number_2(conversion, 'buyQuantity', 'buyAmount'),
'price': self.safe_number(conversion, 'buyPrice'),
'fee': None,
}
def fetch_convert_currencies(self, params={}) -> Currencies:
"""
fetches all available currencies that can be converted
https://docs.woox.io/#get-quote-asset-info
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an associative dictionary of currencies
"""
self.load_markets()
response = self.v3PrivateGetConvertAssetInfo(params)
#
# {
# "success": True,
# "rows": [
# {
# "token": "BTC",
# "tick": 0.0001,
# "createdTime": "1575014248.99", # Unix epoch time in seconds
# "updatedTime": "1575014248.99" # Unix epoch time in seconds
# },
# ]
# }
#
result: dict = {}
data = self.safe_list(response, 'rows', [])
for i in range(0, len(data)):
entry = data[i]
id = self.safe_string(entry, 'token')
code = self.safe_currency_code(id)
result[code] = {
'info': entry,
'id': id,
'code': code,
'networks': None,
'type': None,
'name': None,
'active': None,
'deposit': None,
'withdraw': None,
'fee': None,
'precision': self.safe_number(entry, 'tick'),
'limits': {
'amount': {
'min': None,
'max': None,
},
'withdraw': {
'min': None,
'max': None,
},
'deposit': {
'min': None,
'max': None,
},
},
'created': self.safe_timestamp(entry, 'createdTime'),
}
return result
def default_network_code_for_currency(self, code):
currencyItem = self.currency(code)
networks = currencyItem['networks']
networkKeys = list(networks.keys())
for i in range(0, len(networkKeys)):
network = networkKeys[i]
if network == 'ETH':
return network
# if it was not returned according to above options, then return the first network of currency
return self.safe_value(networkKeys, 0)
def set_sandbox_mode(self, enable: bool):
super(woo, self).set_sandbox_mode(enable)
self.options['sandboxMode'] = enable