2859 lines
126 KiB
Python
2859 lines
126 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.deepcoin import ImplicitAPI
|
|
import hashlib
|
|
from ccxt.base.types import Any, Balances, Currency, DepositAddress, Int, LedgerEntry, Market, Num, Order, OrderBook, OrderSide, OrderType, Position, Str, Strings, Ticker, Tickers, FundingRate, FundingRates, Trade, Transaction, TransferEntry
|
|
from typing import List
|
|
from ccxt.base.errors import ExchangeError
|
|
from ccxt.base.errors import ArgumentsRequired
|
|
from ccxt.base.errors import BadRequest
|
|
from ccxt.base.errors import InsufficientFunds
|
|
from ccxt.base.errors import InvalidOrder
|
|
from ccxt.base.errors import OrderNotFound
|
|
from ccxt.base.errors import NotSupported
|
|
from ccxt.base.errors import NullResponse
|
|
from ccxt.base.decimal_to_precision import TICK_SIZE
|
|
from ccxt.base.precise import Precise
|
|
|
|
|
|
class deepcoin(Exchange, ImplicitAPI):
|
|
|
|
def describe(self) -> Any:
|
|
return self.deep_extend(super(deepcoin, self).describe(), {
|
|
'id': 'deepcoin',
|
|
'name': 'DeepCoin',
|
|
'countries': ['SG'], # Singapore
|
|
'rateLimit': 200, # 5 times per second
|
|
'version': 'v1',
|
|
'certified': False,
|
|
'pro': True,
|
|
'has': {
|
|
'CORS': None,
|
|
'spot': True,
|
|
'margin': True,
|
|
'swap': True,
|
|
'future': False,
|
|
'option': False,
|
|
'addMargin': False,
|
|
'cancelAllOrders': True,
|
|
'cancelAllOrdersAfter': False,
|
|
'cancelOrder': True,
|
|
'cancelOrders': True,
|
|
'cancelWithdraw': False,
|
|
'closePosition': True,
|
|
'createConvertTrade': False,
|
|
'createDepositAddress': False,
|
|
'createLimitBuyOrder': True,
|
|
'createLimitOrder': True,
|
|
'createLimitSellOrder': True,
|
|
'createMarketBuyOrder': True,
|
|
'createMarketBuyOrderWithCost': True,
|
|
'createMarketOrder': True,
|
|
'createMarketOrderWithCost': True,
|
|
'createMarketSellOrder': True,
|
|
'createMarketSellOrderWithCost': True,
|
|
'createOrder': True,
|
|
'createOrders': False,
|
|
'createOrderWithTakeProfitAndStopLoss': True,
|
|
'createPostOnlyOrder': True,
|
|
'createReduceOnlyOrder': True,
|
|
'createStopLossOrder': False,
|
|
'createTakeProfitOrder': False,
|
|
'createTrailingAmountOrder': False,
|
|
'createTrailingPercentOrder': False,
|
|
'createTriggerOrder': True,
|
|
'editOrder': True,
|
|
'fetchAccounts': False,
|
|
'fetchBalance': True,
|
|
'fetchCanceledAndClosedOrders': True,
|
|
'fetchCanceledOrders': True,
|
|
'fetchClosedOrder': True,
|
|
'fetchClosedOrders': True,
|
|
'fetchConvertCurrencies': False,
|
|
'fetchConvertQuote': False,
|
|
'fetchConvertTrade': False,
|
|
'fetchConvertTradeHistory': False,
|
|
'fetchCurrencies': False,
|
|
'fetchDepositAddress': True,
|
|
'fetchDepositAddresses': True,
|
|
'fetchDeposits': True,
|
|
'fetchDepositsWithdrawals': False,
|
|
'fetchDepositWithdrawFees': False,
|
|
'fetchFundingHistory': False,
|
|
'fetchFundingRate': True,
|
|
'fetchFundingRateHistory': True,
|
|
'fetchFundingRates': True,
|
|
'fetchIndexOHLCV': True,
|
|
'fetchLedger': True,
|
|
'fetchLeverage': False,
|
|
'fetchLeverageTiers': False,
|
|
'fetchMarginAdjustmentHistory': False,
|
|
'fetchMarginMode': False,
|
|
'fetchMarkets': True,
|
|
'fetchMarkOHLCV': True,
|
|
'fetchMyTrades': True,
|
|
'fetchOHLCV': True,
|
|
'fetchOpenInterest': False,
|
|
'fetchOpenInterestHistory': False,
|
|
'fetchOpenOrder': True,
|
|
'fetchOpenOrders': True,
|
|
'fetchOrder': False,
|
|
'fetchOrderBook': True,
|
|
'fetchOrders': False,
|
|
'fetchOrderTrades': True,
|
|
'fetchPosition': True,
|
|
'fetchPositionHistory': False,
|
|
'fetchPositionMode': False,
|
|
'fetchPositions': True,
|
|
'fetchPositionsForSymbol': True,
|
|
'fetchPositionsHistory': True,
|
|
'fetchPremiumIndexOHLCV': False,
|
|
'fetchStatus': False,
|
|
'fetchTicker': False,
|
|
'fetchTickers': True,
|
|
'fetchTime': False,
|
|
'fetchTrades': True,
|
|
'fetchTradingFee': False,
|
|
'fetchTradingFees': False,
|
|
'fetchTransactions': False,
|
|
'fetchTransfers': False,
|
|
'fetchWithdrawals': True,
|
|
'reduceMargin': False,
|
|
'sandbox': False,
|
|
'setLeverage': True,
|
|
'setMargin': False,
|
|
'setMarginMode': False,
|
|
'setPositionMode': False,
|
|
'transfer': True,
|
|
'withdraw': False,
|
|
},
|
|
'timeframes': {
|
|
'1m': '1m',
|
|
'5m': '5m',
|
|
'15m': '15m',
|
|
'30m': '30m',
|
|
'1h': '1H',
|
|
'4h': '4H',
|
|
'12h': '12H',
|
|
'1d': '1D',
|
|
'1w': '1W',
|
|
'1M': '1M',
|
|
'1y': '1Y',
|
|
},
|
|
'urls': {
|
|
'logo': 'https://github.com/user-attachments/assets/671bd35c-770e-4935-9070-f8fb114f79c4',
|
|
'api': {
|
|
'public': 'https://api.deepcoin.com',
|
|
'private': 'https://api.deepcoin.com',
|
|
},
|
|
'www': 'https://www.deepcoin.com/',
|
|
'doc': 'https://www.deepcoin.com/docs',
|
|
'referral': {
|
|
'url': 'https://s.deepcoin.com/UzkyODgy',
|
|
'discount': 0.1,
|
|
},
|
|
},
|
|
'api': {
|
|
'public': {
|
|
'get': {
|
|
'deepcoin/market/books': 1,
|
|
'deepcoin/market/candles': 1,
|
|
'deepcoin/market/instruments': 1,
|
|
'deepcoin/market/tickers': 1,
|
|
'deepcoin/market/index-candles': 1,
|
|
'deepcoin/market/trades': 1,
|
|
'deepcoin/market/mark-price-candles': 1,
|
|
'deepcoin/market/step-margin': 5,
|
|
},
|
|
},
|
|
'private': {
|
|
'get': {
|
|
'deepcoin/account/balances': 5,
|
|
'deepcoin/account/bills': 5,
|
|
'deepcoin/account/positions': 5,
|
|
'deepcoin/trade/fills': 5,
|
|
'deepcoin/trade/orderByID': 5,
|
|
'deepcoin/trade/finishOrderByID': 5,
|
|
'deepcoin/trade/orders-history': 5,
|
|
'deepcoin/trade/v2/orders-pending': 5,
|
|
'deepcoin/trade/funding-rate': 5,
|
|
'deepcoin/trade/fund-rate/current-funding-rate': 5,
|
|
'deepcoin/trade/fund-rate/history': 5,
|
|
'deepcoin/trade/trigger-orders-pending': 5,
|
|
'deepcoin/trade/trigger-orders-history': 5,
|
|
'deepcoin/copytrading/support-contracts': 5,
|
|
'deepcoin/copytrading/leader-position': 5,
|
|
'deepcoin/copytrading/estimate-profit': 5,
|
|
'deepcoin/copytrading/history-profit': 5,
|
|
'deepcoin/copytrading/follower-rank': 5,
|
|
'deepcoin/internal-transfer/support': 5,
|
|
'deepcoin/internal-transfer/history-order': 5,
|
|
'deepcoin/rebate/config': 5,
|
|
'deepcoin/agents/users': 5,
|
|
'deepcoin/agents/users/rebate-list': 5,
|
|
'deepcoin/agents/users/rebates': 5,
|
|
'deepcoin/asset/deposit-list': 5,
|
|
'deepcoin/asset/withdraw-list': 5,
|
|
'deepcoin/asset/recharge-chain-list': 5,
|
|
'deepcoin/listenkey/acquire': 5,
|
|
'deepcoin/listenkey/extend': 5,
|
|
},
|
|
'post': {
|
|
'deepcoin/account/set-leverage': 5,
|
|
'deepcoin/trade/order': 5,
|
|
'deepcoin/trade/replace-order': 5,
|
|
'deepcoin/trade/cancel-order': 5,
|
|
'deepcoin/trade/batch-cancel-order': 5,
|
|
'deepcoin/trade/cancel-trigger-order': 1 / 6,
|
|
'deepcoin/trade/swap/cancel-all': 5,
|
|
'deepcoin/trade/trigger-order': 5,
|
|
'deepcoin/trade/batch-close-position': 5,
|
|
'deepcoin/trade/replace-order-sltp': 5,
|
|
'deepcoin/trade/close-position-by-ids': 5,
|
|
'deepcoin/copytrading/leader-settings': 5,
|
|
'deepcoin/copytrading/set-contracts': 5,
|
|
'deepcoin/internal-transfer': 5,
|
|
'deepcoin/rebate/config': 5,
|
|
'deepcoin/asset/transfer': 5,
|
|
},
|
|
},
|
|
},
|
|
'fees': {
|
|
'trading': {
|
|
'taker': self.parse_number('0.0015'),
|
|
'maker': self.parse_number('0.0010'),
|
|
},
|
|
},
|
|
'features': {
|
|
'spot': {
|
|
'sandbox': False,
|
|
'createOrder': {
|
|
'marginMode': True,
|
|
'triggerPrice': True,
|
|
'triggerPriceType': {
|
|
'last': True,
|
|
'mark': False,
|
|
'index': False,
|
|
},
|
|
'triggerDirection': False,
|
|
'stopLossPrice': True,
|
|
'takeProfitPrice': True,
|
|
'attachedStopLossTakeProfit': {
|
|
'triggerPriceType': {
|
|
'last': False,
|
|
'mark': False,
|
|
'index': False,
|
|
},
|
|
'price': True,
|
|
},
|
|
'timeInForce': {
|
|
'IOC': True,
|
|
'FOK': True,
|
|
'PO': True,
|
|
'GTD': False,
|
|
},
|
|
'hedged': True,
|
|
'trailing': False,
|
|
'marketBuyRequiresPrice': False,
|
|
},
|
|
'createOrders': None,
|
|
'fetchMyTrades': {
|
|
'marginMode': False,
|
|
'limit': 100,
|
|
'daysBack': 60,
|
|
'untilDays': None,
|
|
'symbolRequired': True,
|
|
},
|
|
'fetchOrder': None,
|
|
'fetchOpenOrders': {
|
|
'marginMode': False,
|
|
'limit': 100,
|
|
'trigger': True,
|
|
'trailing': False,
|
|
'symbolRequired': True,
|
|
},
|
|
'fetchOrders': None,
|
|
'fetchClosedOrders': {
|
|
'marginMode': False,
|
|
'limit': 100,
|
|
'daysBack': None,
|
|
'daysBackCanceled': None,
|
|
'untilDays': None,
|
|
'trigger': True,
|
|
'trailing': False,
|
|
'symbolRequired': True,
|
|
},
|
|
'fetchOHLCV': {
|
|
'limit': 300,
|
|
},
|
|
},
|
|
'swap': {
|
|
'linear': {
|
|
'extends': 'spot',
|
|
},
|
|
'inverse': {
|
|
'extends': 'spot',
|
|
},
|
|
},
|
|
},
|
|
'requiredCredentials': {
|
|
'apiKey': True,
|
|
'secret': True,
|
|
'password': True,
|
|
},
|
|
'precisionMode': TICK_SIZE,
|
|
'options': {
|
|
'recvWindow': 5000,
|
|
'defaultNetworks': {
|
|
'ETH': 'ERC20',
|
|
'USDT': 'TRC20',
|
|
'USDC': 'ERC20',
|
|
},
|
|
'networks': {
|
|
'ERC20': 'ERC20',
|
|
'TRC20': 'TRC20',
|
|
'ARB': 'ARBITRUM',
|
|
'BSC': 'BSC(BEP20)',
|
|
'SOL': 'SOL',
|
|
'BTC': 'Bitcoin',
|
|
'ADA': 'Cardano',
|
|
},
|
|
'networksById': {
|
|
},
|
|
'fetchMarkets': {
|
|
'types': ['spot', 'swap'], # spot, swap,
|
|
},
|
|
'timeInForce': {
|
|
'GTC': 'GTC', # Good Till Cancel
|
|
'IOC': 'IOC', # Immediate Or Cancel
|
|
'PO': 'PO', # Post Only
|
|
},
|
|
'exchangeType': {
|
|
'spot': 'SPOT',
|
|
'swap': 'SWAP',
|
|
'SPOT': 'SPOT',
|
|
'SWAP': 'SWAP',
|
|
},
|
|
'accountsByType': {
|
|
'spot': 1,
|
|
'fund': 2,
|
|
'rebate': 3,
|
|
'inverse': 5,
|
|
'linear': 7,
|
|
'demo': 10,
|
|
},
|
|
},
|
|
'commonCurrencies': {},
|
|
'exceptions': {
|
|
'exact': {
|
|
'24': OrderNotFound, # {"code":"0","msg":"","data":{"ordId":"","clOrdId":"","sCode":"24","sMsg":"OrderNotFound:1"}}
|
|
'31': InsufficientFunds, # {"code":"0","msg":"","data":{"ordId":"","clOrdId":"","tag":"","sCode":"31","sMsg":"NotEnoughPositionToClose:Position=0"}}
|
|
'36': InsufficientFunds, # {"code":"0","msg":"","data":{"ordId":"","clOrdId":"","tag":"","sCode":"36","sMsg":"InsufficientMoney:-0.000004"}}
|
|
'44': BadRequest, # {"code":"0","msg":"","data":{"ordId":"","clOrdId":"","tag":"","sCode":"44","sMsg":"VolumeNotOnTick"}}
|
|
'49': InvalidOrder, # {"code":"0","msg":"","data":{"ordId":"","clOrdId":"","tag":"","sCode":"49","sMsg":"PriceOutOfUpperLimit:Price\u003eUpperLimitPrice[0.28422]"}}
|
|
'194': InvalidOrder, # {"code":"0","msg":"","data":{"ordId":"","clOrdId":"","tag":"","sCode":"194","sMsg":"LessThanMinVolume"}}
|
|
'195': InvalidOrder, # {"code":"0","msg":"","data":{"ordId":"","clOrdId":"","tag":"","sCode":"195","sMsg":"PositionLessThanMinVolume"}}
|
|
'199': BadRequest, # {"code":"0","msg":"","data":{"instId":"","lever":"","mgnMode":"","mrgPosition":"","sCode":"199","sMsg":"LeverageTooHigh:Amount[10000.0]\u003eLeverage[75.1880]"}}
|
|
'100010': InsufficientFunds, # {"code":"0","msg":"","data":{"retCode":100010,"retMsg":"Balance is insufficient, please deposit first.","retData":{}}}
|
|
'unsupportedAction': BadRequest,
|
|
'localIDNotExist': BadRequest,
|
|
},
|
|
'broad': {
|
|
'no available': NotSupported, # orderbook does not exist: ETHUSD_0.1, no available orderbook data
|
|
'field is required': ArgumentsRequired, # {"code":"51","msg":"The productGroup field is required","data":null}
|
|
'not in acceptable range': BadRequest, # {"code":"51","msg":"The instType value `spot` is not in acceptable range: SPOT,SWAP","data":null}
|
|
'subscription cluster does not "exist"': BadRequest,
|
|
'must be equal or lesser than': BadRequest, # {"code":"51","msg":"The Size value `100` must be equal or lesser than 50","data":null}
|
|
},
|
|
},
|
|
})
|
|
|
|
def handle_market_type_and_params(self, methodName: str, market: Market = None, params={}, defaultValue=None) -> Any:
|
|
instType = self.safe_string(params, 'instType')
|
|
params = self.omit(params, 'instType')
|
|
type = self.safe_string(params, 'type')
|
|
if (type is None) and (instType is not None):
|
|
params = self.extend(params, {'type': instType})
|
|
return super(deepcoin, self).handle_market_type_and_params(methodName, market, params, defaultValue)
|
|
|
|
def convert_to_instrument_type(self, type):
|
|
exchangeTypes = self.safe_dict(self.options, 'exchangeType', {})
|
|
return self.safe_string(exchangeTypes, type, type)
|
|
|
|
def fetch_markets(self, params={}) -> List[Market]:
|
|
"""
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinMarket/getBaseInfo
|
|
|
|
retrieves data on all markets for okcoin
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:returns dict[]: an array of objects representing market data
|
|
"""
|
|
types = ['spot', 'swap']
|
|
fetchMarketsOption = self.safe_dict(self.options, 'fetchMarkets')
|
|
if fetchMarketsOption is not None:
|
|
types = self.safe_list(fetchMarketsOption, 'types', types)
|
|
else:
|
|
types = self.safe_list(self.options, 'fetchMarkets', types) # backward-support
|
|
promises = []
|
|
result = []
|
|
for i in range(0, len(types)):
|
|
promises.append(self.fetch_markets_by_type(types[i], params))
|
|
promises = promises
|
|
for i in range(0, len(promises)):
|
|
result = self.array_concat(result, promises[i])
|
|
return result
|
|
|
|
def fetch_markets_by_type(self, type, params={}):
|
|
request: dict = {
|
|
'instType': self.convert_to_instrument_type(type),
|
|
}
|
|
response = self.publicGetDeepcoinMarketInstruments(self.extend(request, params))
|
|
#
|
|
# spot
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": [
|
|
# {
|
|
# "instType": "SPOT",
|
|
# "instId": "A-USDT",
|
|
# "uly": "",
|
|
# "baseCcy": "A",
|
|
# "quoteCcy": "USDT",
|
|
# "ctVal": "1",
|
|
# "ctValCcy": "",
|
|
# "listTime": "0",
|
|
# "lever": "1",
|
|
# "tickSz": "0.0001",
|
|
# "lotSz": "0.001",
|
|
# "minSz": "0.5",
|
|
# "ctType": "",
|
|
# "alias": "",
|
|
# "state": "live",
|
|
# "maxLmtSz": "7692307",
|
|
# "maxMktSz": "7692307"
|
|
# }
|
|
# ]
|
|
# }
|
|
#
|
|
dataResponse = self.safe_list(response, 'data', [])
|
|
return self.parse_markets(dataResponse)
|
|
|
|
def parse_market(self, market: dict) -> Market:
|
|
#
|
|
# spot markets
|
|
#
|
|
# {
|
|
# "instType": "SPOT",
|
|
# "instId": "A-USDT",
|
|
# "uly": "",
|
|
# "baseCcy": "A",
|
|
# "quoteCcy": "USDT",
|
|
# "ctVal": "1",
|
|
# "ctValCcy": "",
|
|
# "listTime": "0",
|
|
# "lever": "1",
|
|
# "tickSz": "0.0001",
|
|
# "lotSz": "0.001",
|
|
# "minSz": "0.5",
|
|
# "ctType": "",
|
|
# "alias": "",
|
|
# "state": "live",
|
|
# "maxLmtSz": "7692307",
|
|
# "maxMktSz": "7692307"
|
|
# }
|
|
#
|
|
# swap markets
|
|
#
|
|
# {
|
|
# "instType": "SWAP",
|
|
# "instId": "ZORA-USDT-SWAP",
|
|
# "uly": "",
|
|
# "baseCcy": "ZORA",
|
|
# "quoteCcy": "USDT",
|
|
# "ctVal": "1",
|
|
# "ctValCcy": "",
|
|
# "listTime": "0",
|
|
# "lever": "20",
|
|
# "tickSz": "0.00001",
|
|
# "lotSz": "1",
|
|
# "minSz": "1685",
|
|
# "ctType": "",
|
|
# "alias": "",
|
|
# "state": "live",
|
|
# "maxLmtSz": "10000000",
|
|
# "maxMktSz": "10000000"
|
|
# }
|
|
#
|
|
id = self.safe_string(market, 'instId')
|
|
type = self.safe_string_lower(market, 'instType')
|
|
spot = (type == 'spot')
|
|
swap = (type == 'swap')
|
|
baseId = self.safe_string(market, 'baseCcy')
|
|
quoteId = self.safe_string(market, 'quoteCcy', '')
|
|
settleId = None
|
|
settle = None
|
|
base = self.safe_currency_code(baseId)
|
|
quote = self.safe_currency_code(quoteId)
|
|
symbol = base + '/' + quote
|
|
isLinear = None
|
|
if swap:
|
|
isLinear = (quoteId != 'USD')
|
|
settleId = quoteId if isLinear else baseId
|
|
settle = self.safe_currency_code(settleId)
|
|
symbol = symbol + ':' + settle
|
|
fees = self.safe_dict_2(self.fees, type, 'trading', {})
|
|
maxLeverage = self.safe_string(market, 'lever', '1')
|
|
maxLeverage = Precise.string_max(maxLeverage, '1')
|
|
maxMarketSize = self.safe_string(market, 'maxMktSz')
|
|
maxLimitSize = self.safe_string(market, 'maxLmtSz')
|
|
maxAmount = self.parse_number(Precise.string_max(maxMarketSize, maxLimitSize))
|
|
state = self.safe_string(market, 'state')
|
|
return self.extend(fees, {
|
|
'id': id,
|
|
'symbol': symbol,
|
|
'base': base,
|
|
'quote': quote,
|
|
'settle': settle,
|
|
'baseId': baseId,
|
|
'quoteId': quoteId,
|
|
'settleId': settleId,
|
|
'type': type,
|
|
'spot': spot,
|
|
'margin': spot and (Precise.string_gt(maxLeverage, '1')),
|
|
'swap': swap,
|
|
'future': False,
|
|
'option': False,
|
|
'active': state == 'live',
|
|
'contract': swap,
|
|
'linear': isLinear,
|
|
'inverse': (not isLinear) if swap else None,
|
|
'contractSize': self.safe_number(market, 'ctVal') if swap else None,
|
|
'expiry': None,
|
|
'expiryDatetime': None,
|
|
'strike': None,
|
|
'optionType': None,
|
|
'created': None,
|
|
'precision': {
|
|
'amount': self.safe_number(market, 'lotSz'),
|
|
'price': self.safe_number(market, 'tickSz'),
|
|
},
|
|
'limits': {
|
|
'leverage': {
|
|
'min': self.parse_number('1'),
|
|
'max': self.parse_number(maxLeverage),
|
|
},
|
|
'amount': {
|
|
'min': self.safe_number(market, 'minSz'),
|
|
'max': maxAmount,
|
|
},
|
|
'price': {
|
|
'min': None,
|
|
'max': None,
|
|
},
|
|
'cost': {
|
|
'min': None,
|
|
'max': None,
|
|
},
|
|
},
|
|
'info': market,
|
|
})
|
|
|
|
def set_markets(self, markets, currencies=None):
|
|
markets = super(deepcoin, self).set_markets(markets, currencies)
|
|
symbols = list(markets.keys())
|
|
for i in range(0, len(symbols)):
|
|
symbol = symbols[i]
|
|
market = markets[symbol]
|
|
if market['swap']:
|
|
additionalId = market['baseId'] + market['quoteId']
|
|
self.markets_by_id[additionalId] = [market] # some endpoints return swap market id+quote
|
|
return self.markets
|
|
|
|
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://www.deepcoin.com/docs/DeepCoinMarket/marketBooks
|
|
|
|
: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)
|
|
if limit is None:
|
|
limit = 400
|
|
request: dict = {
|
|
'instId': market['id'],
|
|
'sz': limit,
|
|
}
|
|
response = self.publicGetDeepcoinMarketBooks(self.extend(request, params))
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": {
|
|
# "bids": [
|
|
# ["3732.21", "99.6"],
|
|
# ["3732.2", "54.7"]
|
|
# ],
|
|
# "asks": [
|
|
# ["3732.22", "85.1"],
|
|
# ["3732.23", "49.4"]
|
|
# ]
|
|
# }
|
|
# }
|
|
#
|
|
data = self.safe_dict(response, 'data', {})
|
|
return self.parse_order_book(data, symbol, None, 'bids', 'asks', 0, 1)
|
|
|
|
def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
|
|
"""
|
|
fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinMarket/getKlineData
|
|
https://www.deepcoin.com/docs/DeepCoinMarket/getIndexKlineData
|
|
https://www.deepcoin.com/docs/DeepCoinMarket/getMarkKlineData
|
|
|
|
:param str symbol: unified symbol of the market to fetch OHLCV data for
|
|
:param str timeframe: the length of time each candle represents
|
|
:param int [since]: timestamp in ms of the earliest candle to fetch
|
|
:param int [limit]: the maximum amount of candles to fetch
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param int [params.until]: timestamp in ms of the latest candle to fetch
|
|
:param str [params.price]: "mark" or "index" for mark price and index price candles
|
|
:param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
|
|
:returns int[][]: A list of candles ordered, open, high, low, close, volume
|
|
"""
|
|
self.load_markets()
|
|
maxLimit = 300
|
|
paginate = False
|
|
paginate, params = self.handle_option_and_params(params, 'fetchOHLCV', 'paginate', False)
|
|
if paginate:
|
|
params = self.extend(params, {'calculateUntil': True})
|
|
return self.fetch_paginated_call_deterministic('fetchOHLCV', symbol, since, limit, timeframe, params, maxLimit)
|
|
market = self.market(symbol)
|
|
price = self.safe_string(params, 'price')
|
|
params = self.omit(params, 'price')
|
|
bar = self.safe_string(self.timeframes, timeframe, timeframe)
|
|
request: dict = {
|
|
'instId': market['id'],
|
|
'bar': bar,
|
|
}
|
|
if limit is not None:
|
|
request['limit'] = limit
|
|
until = self.safe_integer(params, 'until')
|
|
if until is not None:
|
|
request['after'] = until
|
|
params = self.omit(params, 'until')
|
|
calculateUntil = self.safe_bool(params, 'calculateUntil', False)
|
|
if calculateUntil:
|
|
params = self.omit(params, 'calculateUntil')
|
|
if since is not None:
|
|
# the exchange do not have a since param for self endpoint
|
|
# we canlculate until(after) for correct pagination
|
|
duration = self.parse_timeframe(timeframe)
|
|
numberOfCandles = maxLimit if (limit is None) else limit
|
|
endTime = since + (duration * numberOfCandles) * 1000
|
|
if until is not None:
|
|
endTime = min(endTime, until)
|
|
now = self.milliseconds()
|
|
request['after'] = min(endTime, now)
|
|
response = None
|
|
if price == 'mark':
|
|
response = self.publicGetDeepcoinMarketMarkPriceCandles(self.extend(request, params))
|
|
elif price == 'index':
|
|
response = self.publicGetDeepcoinMarketIndexCandles(self.extend(request, params))
|
|
else:
|
|
response = self.publicGetDeepcoinMarketCandles(self.extend(request, params))
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data":[
|
|
# [
|
|
# "1760221800000",
|
|
# "3739.08",
|
|
# "3741.95",
|
|
# "3737.75",
|
|
# "3740.1",
|
|
# "2849",
|
|
# "1065583.744"
|
|
# ],
|
|
# [
|
|
# "1760221740000",
|
|
# "3742.36",
|
|
# "3743.01",
|
|
# "3736.83",
|
|
# "3739.08",
|
|
# "2723",
|
|
# "1018290.723"
|
|
# ]
|
|
# ]
|
|
# }
|
|
#
|
|
data = self.safe_list(response, 'data', [])
|
|
return self.parse_ohlcvs(data, market, timeframe, since, limit)
|
|
|
|
def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
|
|
"""
|
|
fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinMarket/getMarketTickers
|
|
|
|
:param str[] [symbols]: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
|
|
"""
|
|
self.load_markets()
|
|
symbols = self.market_symbols(symbols)
|
|
market = self.get_market_from_symbols(symbols)
|
|
marketType = None
|
|
marketType, params = self.handle_market_type_and_params('fetchTickers', market, params)
|
|
request: dict = {
|
|
'instType': self.convert_to_instrument_type(marketType),
|
|
}
|
|
response = self.publicGetDeepcoinMarketTickers(self.extend(request, params))
|
|
tickers = self.safe_list(response, 'data', [])
|
|
return self.parse_tickers(tickers, symbols)
|
|
|
|
def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
|
|
#
|
|
# {
|
|
# "instType": "SWAP",
|
|
# "instId": "BTC-USD-SWAP",
|
|
# "last": "114113.3",
|
|
# "lastSz": "",
|
|
# "askPx": "114113.5",
|
|
# "askSz": "56280",
|
|
# "bidPx": "114113.2",
|
|
# "bidSz": "63220",
|
|
# "open24h": "113214.7",
|
|
# "high24h": "116039.2",
|
|
# "low24h": "113214.7",
|
|
# "volCcy24h": "73.31475724",
|
|
# "vol24h": "8406739",
|
|
# "sodUtc0": "",
|
|
# "sodUtc8": "",
|
|
# "ts": "1760367816000"
|
|
# }
|
|
#
|
|
timestamp = self.safe_integer(ticker, 'ts')
|
|
marketId = self.safe_string(ticker, 'instId')
|
|
market = self.safe_market(marketId, market, '-')
|
|
symbol = market['symbol']
|
|
last = self.safe_string(ticker, 'last')
|
|
open = self.safe_string(ticker, 'open24h')
|
|
quoteVolume = self.safe_string(ticker, 'volCcy24h')
|
|
baseVolume = self.safe_string(ticker, 'vol24h')
|
|
if market['swap'] and market['inverse']:
|
|
temp = baseVolume
|
|
baseVolume = quoteVolume
|
|
quoteVolume = temp
|
|
high = self.safe_string(ticker, 'high24h')
|
|
low = self.safe_string(ticker, 'low24h')
|
|
return self.safe_ticker({
|
|
'symbol': symbol,
|
|
'timestamp': timestamp,
|
|
'datetime': self.iso8601(timestamp),
|
|
'high': high,
|
|
'low': low,
|
|
'bid': self.safe_string(ticker, 'bidPx'),
|
|
'bidVolume': self.safe_string(ticker, 'bidSz'),
|
|
'ask': self.safe_string(ticker, 'askPx'),
|
|
'askVolume': self.safe_string(ticker, 'askSz'),
|
|
'vwap': None,
|
|
'open': open,
|
|
'close': last,
|
|
'last': last,
|
|
'previousClose': None,
|
|
'change': None,
|
|
'percentage': None,
|
|
'average': None,
|
|
'baseVolume': baseVolume,
|
|
'quoteVolume': quoteVolume,
|
|
'markPrice': None,
|
|
'indexPrice': None,
|
|
'info': ticker,
|
|
}, 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://www.deepcoin.com/docs/DeepCoinMarket/getTrades
|
|
|
|
: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(default 100, max 500)
|
|
: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 = {
|
|
'instId': market['id'],
|
|
}
|
|
if limit is not None:
|
|
request['limit'] = limit # default 100, max 500
|
|
productGroup = self.get_product_group_from_market(market)
|
|
request['productGroup'] = productGroup
|
|
response = self.publicGetDeepcoinMarketTrades(self.extend(request, params))
|
|
data = self.safe_list(response, 'data', [])
|
|
return self.parse_trades(data, market, since, limit)
|
|
|
|
def get_product_group_from_market(self, market: Market) -> str:
|
|
productGroup = 'Spot'
|
|
if market['swap']:
|
|
if market['linear']:
|
|
productGroup = 'SwapU'
|
|
else:
|
|
productGroup = 'Swap'
|
|
return productGroup
|
|
|
|
def parse_trade(self, trade: dict, market: Market = None) -> Trade:
|
|
#
|
|
# public fetchTrades
|
|
#
|
|
# {
|
|
# "instId": "ETH-USDT",
|
|
# "tradeId": "1001056388761321",
|
|
# "px": "4095.66",
|
|
# "sz": "0.01311251",
|
|
# "side": "sell",
|
|
# "ts": "1760367870000"
|
|
# }
|
|
#
|
|
# private fetchMyTrades
|
|
# {
|
|
# "instType": "SPOT",
|
|
# "instId": "ETH-USDT",
|
|
# "tradeId": "1001056429613610",
|
|
# "ordId": "1001435238208686",
|
|
# "clOrdId": "",
|
|
# "billId": "10010564296136101",
|
|
# "tag": "",
|
|
# "fillPx": "3791.15",
|
|
# "fillSz": "0.004",
|
|
# "side": "sell",
|
|
# "posSide": "",
|
|
# "execType": "",
|
|
# "feeCcy": "USDT",
|
|
# "fee": "0.0151646",
|
|
# "ts": "1760704540000"
|
|
# }
|
|
#
|
|
marketId = self.safe_string(trade, 'instId')
|
|
market = self.safe_market(marketId, market)
|
|
timestamp = self.safe_integer(trade, 'ts')
|
|
side = self.safe_string(trade, 'side')
|
|
execType = self.safe_string(trade, 'execType')
|
|
fee = None
|
|
feeCost = self.safe_string(trade, 'fee')
|
|
if feeCost is not None:
|
|
feeCurrencyId = self.safe_string(trade, 'feeCcy')
|
|
feeCurrencyCode = self.safe_currency_code(feeCurrencyId)
|
|
fee = {
|
|
'cost': feeCost,
|
|
'currency': feeCurrencyCode,
|
|
}
|
|
return self.safe_trade({
|
|
'info': trade,
|
|
'timestamp': timestamp,
|
|
'datetime': self.iso8601(timestamp),
|
|
'symbol': market['symbol'],
|
|
'id': self.safe_string(trade, 'tradeId'),
|
|
'order': self.safe_string(trade, 'ordId'),
|
|
'type': None,
|
|
'takerOrMaker': self.parse_taker_or_maker(execType),
|
|
'side': side,
|
|
'price': self.safe_string_2(trade, 'fillPx', 'px'),
|
|
'amount': self.safe_string_2(trade, 'fillSz', 'sz'),
|
|
'cost': None,
|
|
'fee': fee,
|
|
}, market)
|
|
|
|
def parse_taker_or_maker(self, execType: Str):
|
|
types = {
|
|
'T': 'taker',
|
|
'M': 'maker',
|
|
}
|
|
return self.safe_string(types, execType, execType)
|
|
|
|
def fetch_balance(self, params={}) -> Balances:
|
|
"""
|
|
query for balance and get the amount of funds available for trading or funds locked in orders
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinAccount/getAccountBalance
|
|
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param str [params.type]: "spot" or "swap", the market type for the balance
|
|
:returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
|
|
"""
|
|
self.load_markets()
|
|
marketType = 'spot'
|
|
marketType, params = self.handle_market_type_and_params('fetchBalance', None, params, marketType)
|
|
request: dict = {
|
|
'instType': self.convert_to_instrument_type(marketType),
|
|
}
|
|
response = self.privateGetDeepcoinAccountBalances(self.extend(request, params))
|
|
return self.parse_balance(response)
|
|
|
|
def parse_balance(self, response) -> Balances:
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": [
|
|
# {
|
|
# "ccy": "USDT",
|
|
# "bal": "74",
|
|
# "frozenBal": "0",
|
|
# "availBal": "74"
|
|
# }
|
|
# ]
|
|
# }
|
|
#
|
|
result: dict = {
|
|
'info': response,
|
|
'timestamp': None,
|
|
'datetime': None,
|
|
}
|
|
balances = self.safe_list(response, 'data', [])
|
|
for i in range(0, len(balances)):
|
|
balance = balances[i]
|
|
symbol = self.safe_string(balance, 'ccy')
|
|
code = self.safe_currency_code(symbol)
|
|
account = self.account()
|
|
account['total'] = self.safe_string(balance, 'bal')
|
|
account['used'] = self.safe_string(balance, 'frozenBal')
|
|
account['free'] = self.safe_string(balance, 'availBal')
|
|
result[code] = account
|
|
return self.safe_balance(result)
|
|
|
|
def fetch_deposits(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
|
|
"""
|
|
fetch all deposits made to an account
|
|
|
|
https://www.deepcoin.com/docs/assets/deposit
|
|
|
|
:param str code: unified currency code
|
|
:param int [since]: the earliest time in ms to fetch deposits for
|
|
:param int [limit]: the maximum number of deposits structures to retrieve
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param int [params.until]: the latest time in ms to fetch entries for
|
|
:param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
|
|
:returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
|
|
"""
|
|
self.load_markets()
|
|
paginate = False
|
|
paginate, params = self.handle_option_and_params(params, 'fetchDeposits', 'paginate', False)
|
|
if paginate:
|
|
return self.fetch_paginated_call_cursor('fetchDeposits', code, since, limit, params, 'code', None, 1, 50)
|
|
request: dict = {}
|
|
currency = None
|
|
if code is not None:
|
|
currency = self.currency(code)
|
|
request['coin'] = currency['id']
|
|
if since is not None:
|
|
request['startTime'] = since
|
|
if limit is not None:
|
|
request['size'] = limit
|
|
until = self.safe_integer(params, 'until')
|
|
if until is not None:
|
|
request['endTime'] = until
|
|
params = self.omit(params, 'until')
|
|
response = self.privateGetDeepcoinAssetDepositList(self.extend(request, params))
|
|
data = self.safe_dict(response, 'data', {})
|
|
items = self.safe_list(data, 'data', [])
|
|
transactionParams: dict = {
|
|
'type': 'deposit',
|
|
}
|
|
return self.parse_transactions(items, currency, since, limit, transactionParams)
|
|
|
|
def fetch_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
|
|
"""
|
|
fetch all withdrawals made from an account
|
|
|
|
https://www.deepcoin.com/docs/assets/withdraw
|
|
|
|
:param str code: unified currency code of the currency transferred
|
|
:param int [since]: the earliest time in ms to fetch transfers for(default 24 hours ago)
|
|
:param int [limit]: the maximum number of transfer structures to retrieve(default 50, max 200)
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param int [params.until]: the latest time in ms to fetch transfers for(default time now)
|
|
:param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
|
|
:returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
|
|
"""
|
|
self.load_markets()
|
|
paginate = False
|
|
paginate, params = self.handle_option_and_params(params, 'fetchDeposits', 'paginate', False)
|
|
if paginate:
|
|
return self.fetch_paginated_call_cursor('fetchDeposits', code, since, limit, params, 'code', None, 1, 50)
|
|
request: dict = {}
|
|
currency = None
|
|
if code is not None:
|
|
currency = self.currency(code)
|
|
request['coin'] = currency['id']
|
|
if since is not None:
|
|
request['startTime'] = since
|
|
if limit is not None:
|
|
request['size'] = limit
|
|
until = self.safe_integer(params, 'until')
|
|
if until is not None:
|
|
request['endTime'] = until
|
|
params = self.omit(params, 'until')
|
|
response = self.privateGetDeepcoinAssetWithdrawList(self.extend(request, params))
|
|
data = self.safe_dict(response, 'data', {})
|
|
items = self.safe_list(data, 'data', [])
|
|
transactionParams: dict = {
|
|
'type': 'withdrawal',
|
|
}
|
|
return self.parse_transactions(items, currency, since, limit, transactionParams)
|
|
|
|
def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
|
|
#
|
|
# fetchDeposits
|
|
# {
|
|
# "createTime": 1760368656,
|
|
# "txHash": "03fe3244d89e794586222413c61779380da9e9fe5baaa253c38d01a4199a3499",
|
|
# "chainName": "TRC20",
|
|
# "amount": "149",
|
|
# "coin": "USDT",
|
|
# "status": "succeed"
|
|
# }
|
|
#
|
|
txid = self.safe_string(transaction, 'txHash')
|
|
currencyId = self.safe_string(transaction, 'coin')
|
|
code = self.safe_currency_code(currencyId, currency)
|
|
amount = self.safe_number(transaction, 'amount')
|
|
timestamp = self.safe_timestamp(transaction, 'createTime')
|
|
networkId = self.safe_string(transaction, 'chainName')
|
|
network = self.network_id_to_code(networkId)
|
|
status = self.parse_transaction_status(self.safe_string(transaction, 'status'))
|
|
return {
|
|
'info': transaction,
|
|
'id': None,
|
|
'currency': code,
|
|
'amount': amount,
|
|
'network': network,
|
|
'addressFrom': None,
|
|
'addressTo': None,
|
|
'address': self.safe_string(transaction, 'address'),
|
|
'tagFrom': None,
|
|
'tagTo': None,
|
|
'tag': None,
|
|
'status': status,
|
|
'type': None,
|
|
'updated': None,
|
|
'txid': txid,
|
|
'timestamp': timestamp,
|
|
'datetime': self.iso8601(timestamp),
|
|
'internal': None,
|
|
'comment': None,
|
|
'fee': {
|
|
'currency': None,
|
|
'cost': None,
|
|
},
|
|
}
|
|
|
|
def parse_transaction_status(self, status: Str) -> Str:
|
|
statuses: dict = {
|
|
'confirming': 'pending',
|
|
'succeed': 'ok',
|
|
}
|
|
return self.safe_string(statuses, status, status)
|
|
|
|
def fetch_deposit_addresses(self, codes: Strings = None, params={}) -> List[DepositAddress]:
|
|
"""
|
|
fetch deposit addresses for multiple currencies and chain types
|
|
|
|
https://www.deepcoin.com/docs/assets/chainlist
|
|
|
|
:param str[]|None codes: list of unified currency codes, default is None
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:returns dict: a list of `address structures <https://docs.ccxt.com/#/?id=address-structure>`
|
|
"""
|
|
self.load_markets()
|
|
if codes is None:
|
|
raise ArgumentsRequired(self.id + ' fetchDepositAddresses requires a list with one currency code')
|
|
length = len(codes)
|
|
if length != 1:
|
|
raise NotSupported(self.id + ' fetchDepositAddresses requires a list with one currency code')
|
|
code = codes[0]
|
|
currency = self.currency(code)
|
|
request: dict = {
|
|
'currency_id': currency['id'],
|
|
'lang': 'en',
|
|
}
|
|
response = self.privateGetDeepcoinAssetRechargeChainList(self.extend(request, params))
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": {
|
|
# "list": [
|
|
# {
|
|
# "chain": "TRC20",
|
|
# "state": 1,
|
|
# "remind": "Only support deposits and withdrawals via TRC20 network. If you send it via other address by mistake, it will not be credited and will result in the permanent loss of your deposit.",
|
|
# "inNotice": "",
|
|
# "actLogo": "",
|
|
# "address": "TNJYDW9Bk87VwfA6s7FtxURLEMHesQbYgF",
|
|
# "hasMemo": False,
|
|
# "memo": "",
|
|
# "estimatedTime": 1,
|
|
# "fastConfig": {
|
|
# "fastLimitNum": 0,
|
|
# "fastBlock": 10,
|
|
# "realBlock": 1
|
|
# }
|
|
# }
|
|
# ]
|
|
# }
|
|
# }
|
|
#
|
|
data = self.safe_dict(response, 'data', {})
|
|
list = self.safe_list(data, 'list', [])
|
|
additionalParams: dict = {
|
|
'currency': code,
|
|
}
|
|
return self.parse_deposit_addresses(list, codes, False, additionalParams)
|
|
|
|
def fetch_deposit_address(self, code: str, params={}) -> DepositAddress:
|
|
"""
|
|
fetch the deposit address for a currency associated with self account
|
|
|
|
https://www.deepcoin.com/docs/assets/chainlist
|
|
|
|
:param str code: unified currency code
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param str [params.network]: unified network code for deposit chain
|
|
:returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
|
|
"""
|
|
self.load_markets()
|
|
network = self.safe_string(params, 'network')
|
|
defaultNetworks = self.safe_dict(self.options, 'defaultNetworks', {})
|
|
defaultNetwork = self.safe_string(defaultNetworks, code)
|
|
network = network if network else defaultNetwork
|
|
if network is not None:
|
|
params = self.omit(params, 'network')
|
|
addressess = self.fetch_deposit_addresses([code], params)
|
|
length = len(addressess)
|
|
address = self.safe_dict(addressess, 0, {})
|
|
if (network is not None) and (length > 1):
|
|
for i in range(0, length):
|
|
entry = addressess[i]
|
|
if entry['network'] == network:
|
|
address = entry
|
|
return address
|
|
|
|
def parse_deposit_address(self, response, currency: Currency = None) -> DepositAddress:
|
|
#
|
|
# {
|
|
# "chain": "TRC20",
|
|
# "state": 1,
|
|
# "remind": "Only support deposits and withdrawals via TRC20 network. If you send it via other address by mistake, it will not be credited and will result in the permanent loss of your deposit.",
|
|
# "inNotice": "",
|
|
# "actLogo": "",
|
|
# "address": "TNJYDW9Bk87VwfA6s7FtxURLEMHesQbYgF",
|
|
# "hasMemo": False,
|
|
# "memo": "",
|
|
# "estimatedTime": 1,
|
|
# "fastConfig": {
|
|
# "fastLimitNum": 0,
|
|
# "fastBlock": 10,
|
|
# "realBlock": 1
|
|
# }
|
|
# }
|
|
#
|
|
chain = self.safe_string(response, 'chain')
|
|
address = self.safe_string(response, 'address')
|
|
self.check_address(address)
|
|
return {
|
|
'info': response,
|
|
'currency': None,
|
|
'network': self.network_id_to_code(chain),
|
|
'address': address,
|
|
'tag': self.safe_string(response, 'memo'),
|
|
}
|
|
|
|
def fetch_ledger(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[LedgerEntry]:
|
|
"""
|
|
fetch the history of changes, actions done by the user or operations that altered the balance of the user
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinAccount/getAccountBills
|
|
|
|
:param str [code]: unified currency code
|
|
:param int [since]: timestamp in ms of the earliest ledger entry
|
|
:param int [limit]: max number of ledger entries to return
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param int [params.until]: timestamp in ms of the latest ledger entry
|
|
:param str [params.type]: 'spot' or 'swap', the market type for the ledger(default 'spot')
|
|
:returns dict[]: a list of `ledger structures <https://docs.ccxt.com/#/?id=ledger>`
|
|
"""
|
|
self.load_markets()
|
|
marketType = 'spot'
|
|
marketType, params = self.handle_market_type_and_params('fetchLedger', None, params, marketType)
|
|
request: dict = {
|
|
'instType': self.convert_to_instrument_type(marketType),
|
|
}
|
|
currency = None
|
|
if code is not None:
|
|
currency = self.currency(code)
|
|
request['ccy'] = currency['id']
|
|
if since is not None:
|
|
request['after'] = since
|
|
if limit is not None:
|
|
request['limit'] = limit
|
|
until = self.safe_integer(params, 'until')
|
|
if until is not None:
|
|
request['before'] = until
|
|
params = self.omit(params, 'until')
|
|
response = self.privateGetDeepcoinAccountBills(self.extend(request, params))
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": [
|
|
# {
|
|
# "billId": "1001044652247714",
|
|
# "ccy": "USDT",
|
|
# "clientId": "",
|
|
# "balChg": "-0.03543537",
|
|
# "bal": "72.41881427",
|
|
# "type": "5",
|
|
# "ts": "1761047448000"
|
|
# },
|
|
# {
|
|
# "billId": "1001044652258368",
|
|
# "ccy": "DOGE",
|
|
# "clientId": "",
|
|
# "balChg": "76",
|
|
# "bal": "76",
|
|
# "type": "2",
|
|
# "ts": "1761051006000"
|
|
# }
|
|
# ]
|
|
# }
|
|
#
|
|
data = self.safe_list(response, 'data', [])
|
|
return self.parse_ledger(data, currency, since, limit)
|
|
|
|
def parse_ledger_entry(self, item: dict, currency: Currency = None) -> LedgerEntry:
|
|
#
|
|
# {
|
|
# "billId": "1001044652247714",
|
|
# "ccy": "USDT",
|
|
# "clientId": "",
|
|
# "balChg": "-0.03543537",
|
|
# "bal": "72.41881427",
|
|
# "type": "5",
|
|
# "ts": "1761047448000"
|
|
# }
|
|
#
|
|
timestamp = self.safe_integer(item, 'ts')
|
|
change = self.safe_string(item, 'balChg')
|
|
amount = Precise.string_abs(change)
|
|
direction = 'out' if Precise.string_lt(change, '0') else 'in'
|
|
currencyId = self.safe_string(item, 'ccy')
|
|
currency = self.safe_currency(currencyId, currency)
|
|
type = self.safe_string(item, 'type')
|
|
return self.safe_ledger_entry({
|
|
'info': item,
|
|
'id': self.safe_string(item, 'billId'),
|
|
'direction': direction,
|
|
'account': None,
|
|
'referenceAccount': None,
|
|
'referenceId': None,
|
|
'type': self.parse_ledger_entry_type(type),
|
|
'currency': currency['code'],
|
|
'amount': amount,
|
|
'timestamp': timestamp,
|
|
'datetime': self.iso8601(timestamp),
|
|
'before': None,
|
|
'after': self.safe_string(item, 'bal'),
|
|
'status': None,
|
|
'fee': None,
|
|
}, currency)
|
|
|
|
def parse_ledger_entry_type(self, type):
|
|
ledgerType: dict = {
|
|
'1': 'trade',
|
|
'2': 'trade',
|
|
'3': 'transfer',
|
|
'4': 'transfer',
|
|
'5': 'fee',
|
|
}
|
|
return self.safe_string(ledgerType, type, type)
|
|
|
|
def transfer(self, code: str, amount: float, fromAccount: str, toAccount: str, params={}) -> TransferEntry:
|
|
"""
|
|
transfer currency internally between wallets on the same account
|
|
|
|
https://www.deepcoin.com/docs/assets/transfer
|
|
|
|
:param str code: unified currency code
|
|
:param float amount: amount to transfer
|
|
:param str fromAccount: account to transfer from('spot', 'inverse', 'linear', 'fund', 'rebate' or 'demo')
|
|
:param str toAccount: account to transfer to('spot', 'inverse', 'linear', 'fund', 'rebate' or 'demo')
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param str [params.userId]: user id
|
|
:returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
|
|
"""
|
|
userId = None
|
|
userId, params = self.handle_option_and_params(params, 'transfer', 'userId')
|
|
userId = userId if userId else self.safe_string(params, 'uid')
|
|
if userId is None:
|
|
raise ArgumentsRequired(self.id + ' transfer() requires a userId parameter')
|
|
self.load_markets()
|
|
currency = self.currency(code)
|
|
accountsByType = self.safe_dict(self.options, 'accountsByType', {})
|
|
fromId = self.safe_string(accountsByType, fromAccount, fromAccount)
|
|
toId = self.safe_string(accountsByType, toAccount, toAccount)
|
|
request: dict = {
|
|
'currency_id': currency['id'],
|
|
'amount': self.currency_to_precision(code, amount),
|
|
'from_id': fromId,
|
|
'to_id': toId,
|
|
'uid': userId,
|
|
}
|
|
response = self.privatePostDeepcoinAssetTransfer(self.extend(request, params))
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": {
|
|
# "retCode": 0,
|
|
# "retMsg": "",
|
|
# "retData": {}
|
|
# }
|
|
# }
|
|
#
|
|
data = self.safe_dict(response, 'data', {})
|
|
transfer = self.parse_transfer(data, currency)
|
|
transferOptions = self.safe_dict(self.options, 'transfer', {})
|
|
fillResponseFromRequest = self.safe_bool(transferOptions, 'fillResponseFromRequest', True)
|
|
if fillResponseFromRequest:
|
|
transfer['fromAccount'] = fromAccount
|
|
transfer['toAccount'] = toAccount
|
|
transfer['amount'] = amount
|
|
return transfer
|
|
|
|
def parse_transfer(self, transfer: dict, currency: Currency = None) -> TransferEntry:
|
|
#
|
|
# {
|
|
# "retCode": 0,
|
|
# "retMsg": "",
|
|
# "retData": {}
|
|
# }
|
|
#
|
|
status = self.safe_string(transfer, 'retCode')
|
|
currencyCode = self.safe_currency_code(None, currency)
|
|
return {
|
|
'info': transfer,
|
|
'id': None,
|
|
'timestamp': None,
|
|
'datetime': None,
|
|
'currency': currencyCode,
|
|
'amount': None,
|
|
'fromAccount': None,
|
|
'toAccount': None,
|
|
'status': self.parse_transfer_status(status),
|
|
}
|
|
|
|
def parse_transfer_status(self, status: Str) -> Str:
|
|
if status == '0':
|
|
return 'ok'
|
|
return 'failed'
|
|
|
|
def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
|
|
"""
|
|
create a trade order
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/order
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/triggerOrder
|
|
|
|
: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.clientOrderId]: a unique id for the order
|
|
:param str [params.timeInForce]: *non trigger orders only* 'GTC'(Good Till Cancel), 'IOC'(Immediate Or Cancel) or 'PO'(Post Only)
|
|
:param bool [params.postOnly]: *non trigger orders only* True to place a post only order
|
|
:param bool [params.reduceOnly]: *non trigger orders only* a mark to reduce the position size for margin, swap and future orders
|
|
:param float [params.triggerPrice]: the price a trigger order is triggered at
|
|
:param float [params.stopLoss.triggerPrice]: the price that a stop loss order is triggered at
|
|
:param float [params.takeProfit.triggerPrice]: the price that a take profit order is triggered at
|
|
:param str [params.positionSide]: if position mode is one-way: set to 'net', if position mode is hedge-mode: set to 'long' or 'short'
|
|
:param bool [params.hedged]: *swap only* True for hedged mode, False for one way mode
|
|
:param str [params.marginMode]: *swap only*'cross' or 'isolated', the default is 'cash' for spot and 'cross' for swap
|
|
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
|
|
"""
|
|
self.load_markets()
|
|
market = self.market(symbol)
|
|
triggerPrice = self.safe_string(params, 'triggerPrice')
|
|
request = self.create_order_request(symbol, type, side, amount, price, params)
|
|
response = None
|
|
if triggerPrice is not None:
|
|
# trigger orders
|
|
response = self.privatePostDeepcoinTradeTriggerOrder(request)
|
|
else:
|
|
# regular orders
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": {
|
|
# "ordId": "1001434570213727",
|
|
# "clOrdId": "",
|
|
# "tag": "",
|
|
# "sCode": "0",
|
|
# "sMsg": ""
|
|
# }
|
|
# }
|
|
#
|
|
response = self.privatePostDeepcoinTradeOrder(request)
|
|
data = self.safe_dict(response, 'data', {})
|
|
return self.parse_order(data, market)
|
|
|
|
def create_order_request(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
|
|
"""
|
|
@ignore
|
|
helper function to build request
|
|
"""
|
|
market = self.market(symbol)
|
|
triggerPrice = self.safe_string(params, 'triggerPrice')
|
|
# isTriggerOrder = (triggerPrice is not None) or self.safe_string_2(params, 'stopLossPrice', 'takeProfitPrice') is not None
|
|
isTriggerOrder = (triggerPrice is not None)
|
|
cost = self.safe_string(params, 'cost')
|
|
if cost is not None:
|
|
if not market['spot'] or (triggerPrice is not None):
|
|
raise BadRequest(self.id + ' createOrder() accepts a cost parameter for spot non-trigger market orders only')
|
|
if isTriggerOrder:
|
|
return self.create_trigger_order_request(symbol, type, side, amount, price, params)
|
|
else:
|
|
return self.create_regular_order_request(symbol, type, side, amount, price, params)
|
|
|
|
def create_regular_order_request(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
|
|
"""
|
|
@ignore
|
|
helper function to build request
|
|
:param str symbol: unified symbol of the market to create an order in
|
|
:param str type: 'market' or 'limit'
|
|
:param str side: 'buy' or 'sell'
|
|
:param float amount: how much you want to trade in units of the base currency
|
|
:param float [price]: the price 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.cost]: *spot only* the cost of the order in units of the quote currency, for market orders only
|
|
:param str [params.clientOrderId]: a unique id for the order
|
|
:param str [params.timeInForce]: 'GTC'(Good Till Cancel), 'IOC'(Immediate Or Cancel) or 'PO'(Post Only)
|
|
:param bool [params.postOnly]: True to place a post only order
|
|
:param bool [params.reduceOnly]: a mark to reduce the position size for margin and swap orders
|
|
:param float [params.stopLossPrice]: the price that a stop loss order is triggered at
|
|
:param float [params.takeProfitPrice]: the price that a take profit order is triggered at
|
|
:param str [params.marginMode]: *swap only* 'cross' or 'isolated', the default is 'cash' for spot and 'cross' for swap
|
|
:param str [params.mrgPosition]: *swap only* 'merge' or 'split', the default is 'merge'
|
|
"""
|
|
market = self.market(symbol)
|
|
orderType = type
|
|
orderType, params = self.handle_type_post_only_and_time_in_force(type, params)
|
|
request: dict = {
|
|
'instId': market['id'],
|
|
# 'tdMode': 'cash', # 'cash' for spot, 'cross' or 'isolated' for swap
|
|
# 'ccy': currency['id'], # only applicable to cross MARGIN orders in single-currency margin
|
|
# 'clOrdId': clientOrderId,
|
|
'side': side,
|
|
'ordType': orderType,
|
|
# 'sz': amount or cost
|
|
# 'px': price, # limit orders only
|
|
# 'reduceOnly': False, # a mark to reduce the position size for margin and swap orders
|
|
# 'tgtCcy': 'base_ccy', # spot only 'base_ccy' or 'quote_ccy', the default is 'base_ccy' for spot orders
|
|
# 'tpTriggerPx': takeProfitPrice, # take profit trigger price
|
|
# 'slTriggerPx': stopLossPrice, # stop loss trigger price
|
|
# 'posSide': 'long', # swap only 'long' or 'short'
|
|
# 'mrgPosition': 'merge', # swap only 'merge' or 'split'
|
|
# 'closePosId': 'id', # swap only position ID to close, required in split mode
|
|
}
|
|
clientOrderId = self.safe_string(params, 'clientOrderId')
|
|
if clientOrderId is not None:
|
|
request['clOrdId'] = clientOrderId
|
|
params = self.omit(params, 'clientOrderId')
|
|
stopLoss = self.safe_dict(params, 'stopLoss', {})
|
|
stopLossPrice = self.safe_string(stopLoss, 'triggerPrice')
|
|
if stopLossPrice is not None:
|
|
params = self.omit(params, ['stopLoss'])
|
|
request['slTriggerPx'] = self.price_to_precision(symbol, stopLossPrice)
|
|
takeProfit = self.safe_dict(params, 'takeProfit', {})
|
|
takeProfitPrice = self.safe_string(takeProfit, 'triggerPrice')
|
|
if takeProfitPrice is not None:
|
|
params = self.omit(params, ['takeProfit'])
|
|
request['tpTriggerPx'] = self.price_to_precision(symbol, takeProfitPrice)
|
|
isMarketOrder = (type == 'market')
|
|
if price is not None:
|
|
if isMarketOrder:
|
|
raise BadRequest(self.id + ' createOrder() does not require a price argument for market orders')
|
|
request['px'] = self.price_to_precision(symbol, price)
|
|
elif not isMarketOrder:
|
|
raise BadRequest(self.id + ' createOrder() requires a price argument for limit orders')
|
|
if market['spot']:
|
|
cost = self.safe_string(params, 'cost')
|
|
if cost is not None:
|
|
if not isMarketOrder:
|
|
raise BadRequest(self.id + ' createOrder() accepts a cost parameter for spot market orders only')
|
|
params = self.omit(params, 'cost')
|
|
request['sz'] = self.cost_to_precision(symbol, cost)
|
|
request['tgtCcy'] = 'quote_ccy'
|
|
else:
|
|
request['sz'] = self.amount_to_precision(symbol, amount)
|
|
request['tgtCcy'] = 'base_ccy'
|
|
request['side'] = side
|
|
request['tdMode'] = 'cash'
|
|
else:
|
|
request['sz'] = self.amount_to_precision(symbol, amount)
|
|
marginMode = 'cross'
|
|
marginMode, params = self.handle_margin_mode_and_params('createOrder', params, marginMode)
|
|
request['tdMode'] = marginMode
|
|
mrgPosition = 'merge'
|
|
mrgPosition, params = self.handle_option_and_params(params, 'createOrder', 'mrgPosition', mrgPosition)
|
|
request['mrgPosition'] = mrgPosition
|
|
posSide: Str = None
|
|
reduceOnly = self.safe_bool(params, 'reduceOnly', False)
|
|
if reduceOnly:
|
|
if side == 'buy':
|
|
posSide = 'short'
|
|
elif side == 'sell':
|
|
posSide = 'long'
|
|
else:
|
|
if side == 'buy':
|
|
posSide = 'long'
|
|
elif side == 'sell':
|
|
posSide = 'short'
|
|
request['posSide'] = posSide
|
|
return self.extend(request, params)
|
|
|
|
def create_trigger_order_request(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
|
|
"""
|
|
@ignore
|
|
helper function to build request
|
|
:param str symbol: unified symbol of the market to create an order in
|
|
:param str type: 'market' or 'limit'
|
|
:param str side: 'buy' or 'sell'
|
|
:param float amount: how much you want to trade in units of the base currency
|
|
:param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param bool [params.reduceOnly]: a mark to reduce the position size for margin orders
|
|
:param str [params.marginMode]: *swap only* 'cross' or 'isolated', the default is 'cash' for spot and 'cross' for swap
|
|
"""
|
|
market = self.market(symbol)
|
|
request: dict = {
|
|
'instId': market['id'],
|
|
'productGroup': self.capitalize(market['type']),
|
|
'sz': self.amount_to_precision(symbol, amount),
|
|
'side': side,
|
|
# 'posSide': 'long', # 'long' or 'short' - required when product type is SWAP
|
|
# 'price': price,
|
|
# 'isCrossMargin': 1, # 1 for cross margin, 0 for isolated margin
|
|
'orderType': type,
|
|
# 'triggerPrice': triggerPrice,
|
|
# 'mrgPosition': 'merge', # 'merge' or 'split', the default is 'merge' - required when product type is SWAP
|
|
# 'tdMode': 'cash', # 'cash' for spot, 'cross' or 'isolated' for swap
|
|
}
|
|
triggerPrice = self.safe_string(params, 'triggerPrice')
|
|
# takeProfitPrice = self.safe_string(params, 'takeProfitPrice')
|
|
# stopLossPrice = self.safe_string(params, 'stopLossPrice')
|
|
# isTpOrSlOrder = (takeProfitPrice is not None) or (stopLossPrice is not None)
|
|
# if isTpOrSlOrder:
|
|
# if takeProfitPrice is not None:
|
|
# request['triggerPrice'] = self.price_to_precision(symbol, takeProfitPrice)
|
|
# else:
|
|
# request['triggerPrice'] = self.price_to_precision(symbol, stopLossPrice)
|
|
# }
|
|
# else:
|
|
request['triggerPrice'] = self.price_to_precision(symbol, triggerPrice)
|
|
# }
|
|
if price is not None:
|
|
request['price'] = self.price_to_precision(symbol, price)
|
|
elif type == 'limit':
|
|
raise ArgumentsRequired(self.id + ' createOrder() requires a price argument for limit trigger orders')
|
|
marginMode = 'cross'
|
|
marginMode, params = self.handle_margin_mode_and_params('createOrder', params, marginMode)
|
|
isCrossMargin = 1
|
|
if marginMode == 'isolated':
|
|
isCrossMargin = 0
|
|
reduceOnly = self.safe_bool(params, 'reduceOnly', False)
|
|
params = self.omit(params, 'reduceOnly')
|
|
request['isCrossMargin'] = isCrossMargin
|
|
request['tdMode'] = marginMode
|
|
if market['swap']:
|
|
if reduceOnly:
|
|
if side == 'buy':
|
|
request['posSide'] = 'short'
|
|
elif side == 'sell':
|
|
request['posSide'] = 'long'
|
|
else:
|
|
if side == 'buy':
|
|
request['posSide'] = 'long'
|
|
elif side == 'sell':
|
|
request['posSide'] = 'short'
|
|
mrgPosition = 'merge'
|
|
mrgPosition, params = self.handle_option_and_params(params, 'createOrder', 'mrgPosition', mrgPosition)
|
|
request['mrgPosition'] = mrgPosition
|
|
return self.extend(request, params)
|
|
|
|
def handle_type_post_only_and_time_in_force(self, type: OrderType, params):
|
|
postOnly = False
|
|
postOnly, params = self.handle_post_only(type == 'market', type == 'post_only', params)
|
|
if postOnly:
|
|
type = 'post_only'
|
|
timeInForce = self.handle_time_in_force(params)
|
|
params = self.omit(params, 'timeInForce')
|
|
if (timeInForce is not None) and (timeInForce == 'IOC'):
|
|
type = 'ioc'
|
|
return [type, params]
|
|
|
|
def create_market_order_with_cost(self, symbol: str, side: OrderSide, cost: float, params={}):
|
|
"""
|
|
create a market order by providing the symbol, side and cost
|
|
:param str symbol: unified symbol of the market to create an order in
|
|
:param str side: 'buy' or 'sell'
|
|
: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>`
|
|
"""
|
|
params = self.extend(params, {'cost': cost})
|
|
return self.create_order(symbol, 'market', side, 0, None, params)
|
|
|
|
def create_market_buy_order_with_cost(self, symbol: str, cost: float, params={}) -> Order:
|
|
"""
|
|
create a market buy order by providing the symbol and cost
|
|
:param str symbol: unified symbol of the market to create an order in
|
|
:param float cost: how much you want to trade in units of the quote currency
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
|
|
"""
|
|
params = self.extend(params, {'cost': cost})
|
|
return self.create_order(symbol, 'market', 'buy', 0, None, params)
|
|
|
|
def create_market_sell_order_with_cost(self, symbol: str, cost: float, params={}) -> Order:
|
|
"""
|
|
create a market sell order by providing the symbol and cost
|
|
:param str symbol: unified symbol of the market to create an order in
|
|
:param float cost: how much you want to trade in units of the quote currency
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
|
|
"""
|
|
params = self.extend(params, {'cost': cost})
|
|
return self.create_order(symbol, 'market', 'sell', 0, None, params)
|
|
|
|
def fetch_closed_order(self, id: str, symbol: Str = None, params={}) -> Order:
|
|
"""
|
|
fetches information on a closed order made by the user
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/finishOrderByID
|
|
|
|
: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
|
|
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
|
|
"""
|
|
self.load_markets()
|
|
if symbol is None:
|
|
raise ArgumentsRequired(self.id + ' fetchClosedOrder() requires a symbol argument')
|
|
market = self.market(symbol)
|
|
request: dict = {
|
|
'instId': market['id'],
|
|
'ordId': id,
|
|
}
|
|
response = self.privateGetDeepcoinTradeFinishOrderByID(self.extend(request, params))
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": [
|
|
# {
|
|
# "instType": "SPOT",
|
|
# "instId": "ETH-USDT",
|
|
# "tgtCcy": "",
|
|
# "ccy": "",
|
|
# "ordId": "1001434573319675",
|
|
# "clOrdId": "",
|
|
# "tag": "",
|
|
# "px": "4056.620000000000",
|
|
# "sz": "0.004000",
|
|
# "pnl": "0.000000",
|
|
# "ordType": "market",
|
|
# "side": "buy",
|
|
# "posSide": "",
|
|
# "tdMode": "cash",
|
|
# "accFillSz": "0.004000",
|
|
# "fillPx": "",
|
|
# "tradeId": "",
|
|
# "fillSz": "0.004000",
|
|
# "fillTime": "1760619119000",
|
|
# "avgPx": "",
|
|
# "state": "filled",
|
|
# "lever": "1.000000",
|
|
# "tpTriggerPx": "",
|
|
# "tpTriggerPxType": "",
|
|
# "tpOrdPx": "",
|
|
# "slTriggerPx": "",
|
|
# "slTriggerPxType": "",
|
|
# "slOrdPx": "",
|
|
# "feeCcy": "USDT",
|
|
# "fee": "0.000004",
|
|
# "rebateCcy": "",
|
|
# "source": "",
|
|
# "rebate": "",
|
|
# "category": "normal",
|
|
# "uTime": "1760619119000",
|
|
# "cTime": "1760619119000"
|
|
# }
|
|
# ]
|
|
# }
|
|
#
|
|
data = self.safe_list(response, 'data', [])
|
|
entry = self.safe_dict(data, 0, {})
|
|
return self.parse_order(entry, market)
|
|
|
|
def fetch_open_order(self, id: str, symbol: Str = None, params={}) -> Order:
|
|
"""
|
|
fetch an open order by it's id
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/orderByID
|
|
|
|
:param str id: order id
|
|
:param str symbol: unified market symbol, default is None
|
|
: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()
|
|
if symbol is None:
|
|
raise ArgumentsRequired(self.id + ' fetchClosedOrder() requires a symbol argument')
|
|
market = self.market(symbol)
|
|
request: dict = {
|
|
'instId': market['id'],
|
|
'ordId': id,
|
|
}
|
|
response = self.privateGetDeepcoinTradeOrderByID(self.extend(request, params))
|
|
data = self.safe_list(response, 'data', [])
|
|
length = len(data)
|
|
if length == 0:
|
|
return None
|
|
entry = self.safe_dict(data, 0, {})
|
|
return self.parse_order(entry, market)
|
|
|
|
def fetch_canceled_and_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
|
|
"""
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/ordersHistory
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/triggerOrdersHistory
|
|
|
|
fetches information on multiple canceled and closed orders made by the user
|
|
:param str [symbol]: unified market symbol of the market orders were made in
|
|
:param int [since]: the earliest time in ms to fetch orders for
|
|
:param int [limit]: the maximum number of order structures to retrieve
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param bool [params.trigger]: whether to fetch trigger/algo orders(default False)
|
|
:param str [params.type]: *non trigger orders only* 'spot' or 'swap', the market type for the orders
|
|
:param str [params.state]: *non trigger orders only* 'canceled' or 'filled', the order state to filter by
|
|
:param str [params.OrderType]: *trigger orders only* 'limit' or 'market'
|
|
:param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
|
|
:returns 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, 'fetchCanceledAndClosedOrders', 'paginate')
|
|
if paginate:
|
|
return self.fetch_paginated_call_dynamic('fetchCanceledAndClosedOrders', symbol, since, limit, params)
|
|
trigger = self.safe_bool(params, 'trigger', False)
|
|
methodName = 'fetchCanceledAndClosedOrders'
|
|
methodName, params = self.handle_param_string(params, 'methodName', methodName)
|
|
market: Market = None
|
|
request: dict = {}
|
|
if symbol is not None:
|
|
market = self.market(symbol)
|
|
request['instId'] = market['id']
|
|
marketType = 'spot'
|
|
marketType, params = self.handle_market_type_and_params(methodName, market, params, marketType)
|
|
request['instType'] = self.convert_to_instrument_type(marketType)
|
|
if limit is not None:
|
|
request['limit'] = limit # default 100
|
|
response = None
|
|
if trigger:
|
|
if methodName != 'fetchCanceledAndClosedOrders':
|
|
raise BadRequest(self.id + ' ' + methodName + '() does not support trigger orders')
|
|
if market is None:
|
|
raise ArgumentsRequired(self.id + ' fetchCanceledAndClosedOrders() requires a symbol argument for trigger orders')
|
|
params = self.omit(params, 'trigger')
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": [
|
|
# {
|
|
# "instType": "SWAP",
|
|
# "instId": "DOGE-USDT-SWAP",
|
|
# "ordId": "1001110510915416",
|
|
# "px": "0",
|
|
# "sz": "76",
|
|
# "triggerPx": "0",
|
|
# "triggerPxType": "last",
|
|
# "ordType": "TPSL",
|
|
# "side": "sell",
|
|
# "posSide": "long",
|
|
# "tdMode": "cross",
|
|
# "lever": "2",
|
|
# "triggerTime": "0",
|
|
# "uTime": "1761059366000",
|
|
# "cTime": "1761059218",
|
|
# "errorCode": "0",
|
|
# "errorMsg": ""
|
|
# }
|
|
# ]
|
|
# }
|
|
#
|
|
response = self.privateGetDeepcoinTradeTriggerOrdersHistory(self.extend(request, params))
|
|
else:
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": [
|
|
# {
|
|
# "instType": "SPOT",
|
|
# "instId": "ETH-USDT",
|
|
# "tgtCcy": "",
|
|
# "ccy": "",
|
|
# "ordId": "1001434573319675",
|
|
# "clOrdId": "",
|
|
# "tag": "",
|
|
# "px": "4056.620000000000",
|
|
# "sz": "0.004000",
|
|
# "pnl": "0.000000",
|
|
# "ordType": "market",
|
|
# "side": "buy",
|
|
# "posSide": "",
|
|
# "tdMode": "cash",
|
|
# "accFillSz": "0.004000",
|
|
# "fillPx": "",
|
|
# "tradeId": "",
|
|
# "fillSz": "0.004000",
|
|
# "fillTime": "1760619119000",
|
|
# "avgPx": "",
|
|
# "state": "filled",
|
|
# "lever": "1.000000",
|
|
# "tpTriggerPx": "",
|
|
# "tpTriggerPxType": "",
|
|
# "tpOrdPx": "",
|
|
# "slTriggerPx": "",
|
|
# "slTriggerPxType": "",
|
|
# "slOrdPx": "",
|
|
# "feeCcy": "USDT",
|
|
# "fee": "0.000004",
|
|
# "rebateCcy": "",
|
|
# "source": "",
|
|
# "rebate": "",
|
|
# "category": "normal",
|
|
# "uTime": "1760619119000",
|
|
# "cTime": "1760619119000"
|
|
# }
|
|
# ]
|
|
# }
|
|
#
|
|
response = self.privateGetDeepcoinTradeOrdersHistory(self.extend(request, params))
|
|
# todo handle with since, until and pagination
|
|
data = self.safe_list(response, 'data', [])
|
|
return self.parse_orders(data, market, since, limit)
|
|
|
|
def fetch_canceled_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
|
|
"""
|
|
fetches information on multiple canceled orders made by the user
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/ordersHistory
|
|
|
|
:param str symbol: unified market symbol of the market the 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 str [params.type]: 'spot' or 'swap', the market type for the orders
|
|
:returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
|
|
"""
|
|
methodName = 'fetchCanceledOrders'
|
|
params = self.extend(params, {'methodName': methodName})
|
|
params = self.extend(params, {'state': 'canceled'})
|
|
return self.fetch_canceled_and_closed_orders(symbol, since, limit, params)
|
|
|
|
def fetch_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
|
|
"""
|
|
fetches information on multiple closed orders made by the user
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/ordersHistory
|
|
|
|
:param str symbol: unified market symbol of the market the 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 str [params.type]: 'spot' or 'swap', the market type for the orders
|
|
:returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
|
|
"""
|
|
methodName = 'fetchClosedOrders'
|
|
params = self.extend(params, {'methodName': methodName})
|
|
params = self.extend(params, {'state': 'filled'})
|
|
return self.fetch_canceled_and_closed_orders(symbol, since, limit, params)
|
|
|
|
def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
|
|
"""
|
|
fetch all unfilled currently open orders
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/ordersPendingV2
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/triggerOrdersPending
|
|
|
|
:param str symbol: unified market symbol of the market orders were made in
|
|
:param int [since]: the earliest time in ms to fetch orders for
|
|
:param int [limit]: the maximum number of order structures to retrieve
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param bool [params.trigger]: whether to fetch trigger/algo orders(default False)
|
|
:param int [params.index]: *non trigger orders only* pagination index, default is 1
|
|
:param str [params.orderType]: *trigger orders only* 'limit' or 'market'
|
|
:returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
|
|
"""
|
|
self.load_markets()
|
|
if symbol is None:
|
|
raise ArgumentsRequired(self.id + ' fetchOpenOrders() requires a symbol argument')
|
|
market = self.market(symbol)
|
|
index = self.safe_integer(params, 'index', 1) # todo add pagination handling
|
|
request: dict = {
|
|
'instId': market['id'],
|
|
}
|
|
if limit is not None:
|
|
request['limit'] = limit
|
|
trigger = self.safe_bool(params, 'trigger', False)
|
|
response = None
|
|
if trigger:
|
|
params = self.omit(params, 'trigger')
|
|
request['instType'] = self.convert_to_instrument_type(market['type'])
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": [
|
|
# {
|
|
# "instType": "SPOT",
|
|
# "instId": "DOGE-USDT",
|
|
# "ordId": "1001442305797142",
|
|
# "triggerPx": "0.01",
|
|
# "ordPx": "0.01",
|
|
# "sz": "20",
|
|
# "ordType": "",
|
|
# "side": "buy",
|
|
# "posSide": "",
|
|
# "tdMode": "cash",
|
|
# "triggerOrderType": "Conditional",
|
|
# "triggerPxType": "last",
|
|
# "lever": "",
|
|
# "slPrice": "",
|
|
# "slTriggerPrice": "",
|
|
# "tpPrice": "",
|
|
# "tpTriggerPrice": "",
|
|
# "closeSLTriggerPrice": "",
|
|
# "closeTPTriggerPrice": "",
|
|
# "cTime": "1761814167000",
|
|
# "uTime": "1761814167000"
|
|
# }
|
|
# ]
|
|
# }
|
|
#
|
|
response = self.privateGetDeepcoinTradeTriggerOrdersPending(self.extend(request, params))
|
|
else:
|
|
request['index'] = index
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": [
|
|
# {
|
|
# "instType": "SPOT",
|
|
# "instId": "ETH-USDT",
|
|
# "tgtCcy": "",
|
|
# "ccy": "",
|
|
# "ordId": "1001435158096314",
|
|
# "clOrdId": "",
|
|
# "tag": "",
|
|
# "px": "1000.000000000000",
|
|
# "sz": "0.004000",
|
|
# "pnl": "0.000000",
|
|
# "ordType": "limit",
|
|
# "side": "buy",
|
|
# "posSide": "",
|
|
# "tdMode": "cash",
|
|
# "accFillSz": "0.000000",
|
|
# "fillPx": "",
|
|
# "tradeId": "",
|
|
# "fillSz": "0.000000",
|
|
# "fillTime": "1760695267000",
|
|
# "avgPx": "",
|
|
# "state": "live",
|
|
# "lever": "1",
|
|
# "tpTriggerPx": "",
|
|
# "tpTriggerPxType": "",
|
|
# "tpOrdPx": "",
|
|
# "slTriggerPx": "",
|
|
# "slTriggerPxType": "",
|
|
# "slOrdPx": "",
|
|
# "feeCcy": "USDT",
|
|
# "fee": "0.000000",
|
|
# "rebateCcy": "",
|
|
# "source": "",
|
|
# "rebate": "",
|
|
# "category": "normal",
|
|
# "uTime": "1760695267000",
|
|
# "cTime": "1760695267000"
|
|
# }
|
|
# ]
|
|
# }
|
|
#
|
|
response = self.privateGetDeepcoinTradeV2OrdersPending(self.extend(request, params))
|
|
data = self.safe_list(response, 'data', [])
|
|
return self.parse_orders(data, market, since, limit, {'status': 'open'})
|
|
|
|
def cancel_order(self, id: str, symbol: Str = None, params={}) -> Order:
|
|
"""
|
|
cancels an open order
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/cancelOrder
|
|
|
|
: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 bool [params.trigger]: whether the order is a trigger/algo order(default False)
|
|
:returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
|
|
"""
|
|
self.load_markets()
|
|
if symbol is None:
|
|
raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
|
|
market = self.market(symbol)
|
|
request: dict = {
|
|
'instId': market['id'],
|
|
'ordId': id,
|
|
}
|
|
response = None
|
|
trigger = self.safe_bool(params, 'trigger', False)
|
|
if trigger:
|
|
params = self.omit(params, 'trigger')
|
|
response = self.privatePostDeepcoinTradeCancelTriggerOrder(self.extend(request, params))
|
|
else:
|
|
response = self.privatePostDeepcoinTradeCancelOrder(self.extend(request, params))
|
|
data = self.safe_dict(response, 'data', {})
|
|
return self.parse_order(data, market)
|
|
|
|
def cancel_all_orders(self, symbol: Str = None, params={}) -> List[Order]:
|
|
"""
|
|
cancel all open orders in a market
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/cancelAllOrder
|
|
|
|
:param str symbol: unified market symbol of the market to cancel orders in
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param str [params.marginMode]: *swap only* 'cross' or 'isolated', the default is 'cash' for spot and 'cross' for swap
|
|
:param bool [params.merged]: *swap only* True for merged positions, False for split positions(default True)
|
|
:returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
|
|
"""
|
|
self.load_markets()
|
|
if symbol is None:
|
|
raise ArgumentsRequired(self.id + ' cancelAllOrders() requires a symbol argument')
|
|
market = self.market(symbol)
|
|
if market['spot']:
|
|
raise NotSupported(self.id + ' cancelAllOrders() is not supported for spot markets')
|
|
productGroup = self.get_product_group_from_market(market)
|
|
marginMode = self.safe_string(params, 'marginMode')
|
|
encodedMarginMode = 1
|
|
if marginMode is not None:
|
|
params = self.omit(params, 'marginMode')
|
|
if marginMode == 'isolated':
|
|
encodedMarginMode = 0
|
|
merged = True
|
|
merged, params = self.handle_option_and_params(params, 'cancelAllOrders', 'merged', merged)
|
|
request: dict = {
|
|
'InstrumentID': market['id'],
|
|
'ProductGroup': productGroup,
|
|
'IsCrossMargin': encodedMarginMode,
|
|
'IsMergeMode': 1 if merged else 0,
|
|
}
|
|
response = self.privatePostDeepcoinTradeSwapCancelAll(self.extend(request, params))
|
|
data = self.safe_list(response, 'data', [])
|
|
return self.parse_orders(data, market)
|
|
|
|
def edit_order(self, id: str, symbol: str, type: OrderType, side: OrderSide, amount: Num = None, price: Num = None, params={}):
|
|
"""
|
|
edit a trade order
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/replaceOrder
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/replaceTPSL
|
|
|
|
:param str id: cancel order id
|
|
:param str [symbol]: unified symbol of the market to create an order in(not used in deepcoin editOrder)
|
|
:param str [type]: 'market' or 'limit'(not used in deepcoin editOrder)
|
|
:param str [side]: 'buy' or 'sell'(not used in deepcoin editOrder)
|
|
: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.stopLossPrice]: the price that a stop loss order is triggered at
|
|
:param float [params.takeProfitPrice]: the price that a take profit order is triggered at
|
|
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
|
|
"""
|
|
self.load_markets()
|
|
request: dict = {
|
|
'OrderSysID': id,
|
|
}
|
|
market: Market = None
|
|
if symbol is not None:
|
|
market = self.market(symbol)
|
|
if market['spot']:
|
|
raise NotSupported(self.id + ' editOrder() is not supported for spot markets')
|
|
symbol = market['symbol']
|
|
stopLossPrice = self.safe_number(params, 'stopLossPrice')
|
|
takeProfitPrice = self.safe_number(params, 'takeProfitPrice')
|
|
isTPSL = (stopLossPrice is not None) or (takeProfitPrice is not None)
|
|
response = None
|
|
if isTPSL:
|
|
if (price is not None) or (amount is not None):
|
|
raise BadRequest(self.id + ' editOrder() with stopLossPrice or takeProfitPrice cannot have price or amount. Either use stopLossPrice/takeProfitPrice or price/amount to edit order.')
|
|
if stopLossPrice is not None:
|
|
request['slTriggerPx'] = self.price_to_precision(symbol, stopLossPrice) if symbol else self.number_to_string(stopLossPrice)
|
|
if takeProfitPrice is not None:
|
|
request['tpTriggerPx'] = self.price_to_precision(symbol, takeProfitPrice) if symbol else self.number_to_string(takeProfitPrice)
|
|
params = self.omit(params, ['stopLossPrice', 'takeProfitPrice'])
|
|
response = self.privatePostDeepcoinTradeReplaceOrderSltp(self.extend(request, params))
|
|
else:
|
|
if price is not None:
|
|
if symbol is not None:
|
|
request['price'] = self.price_to_precision(symbol, price)
|
|
else:
|
|
request['price'] = self.number_to_string(price)
|
|
if amount is not None:
|
|
if symbol is not None:
|
|
request['volume'] = self.amount_to_precision(symbol, amount)
|
|
else:
|
|
request['volume'] = self.number_to_string(amount)
|
|
response = self.privatePostDeepcoinTradeReplaceOrder(self.extend(request, params))
|
|
data = self.safe_dict(response, 'data', {})
|
|
return self.parse_order(data)
|
|
|
|
def cancel_orders(self, ids: List[str], symbol: Str = None, params={}) -> List[Order]:
|
|
"""
|
|
cancel multiple orders
|
|
:param str[] ids: order ids
|
|
:param str [symbol]: unified market symbol, default is None
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
|
|
"""
|
|
self.load_markets()
|
|
market: Market = None
|
|
if symbol is not None:
|
|
market = self.market(symbol)
|
|
if market['spot']:
|
|
raise NotSupported(self.id + ' cancelOrders() is not supported for spot markets')
|
|
request: dict = {
|
|
'OrderSysIDs': ids,
|
|
}
|
|
response = self.privatePostDeepcoinTradeBatchCancelOrder(self.extend(request, params))
|
|
data = self.safe_list(response, 'data', [])
|
|
return self.parse_orders(data, market)
|
|
|
|
def parse_order(self, order: dict, market: Market = None) -> Order:
|
|
#
|
|
# regular order
|
|
# {
|
|
# "instType": "SPOT",
|
|
# "instId": "ETH-USDT",
|
|
# "tgtCcy": "",
|
|
# "ccy": "",
|
|
# "ordId": "1001434573319675",
|
|
# "clOrdId": "",
|
|
# "tag": "",
|
|
# "px": "4056.620000000000",
|
|
# "sz": "0.004000",
|
|
# "pnl": "0.000000",
|
|
# "ordType": "market",
|
|
# "side": "buy",
|
|
# "posSide": "",
|
|
# "tdMode": "cash",
|
|
# "accFillSz": "0.004000",
|
|
# "fillPx": "",
|
|
# "tradeId": "",
|
|
# "fillSz": "0.004000",
|
|
# "fillTime": "1760619119000",
|
|
# "avgPx": "",
|
|
# "state": "filled",
|
|
# "lever": "1.000000",
|
|
# "tpTriggerPx": "",
|
|
# "tpTriggerPxType": "",
|
|
# "tpOrdPx": "",
|
|
# "slTriggerPx": "",
|
|
# "slTriggerPxType": "",
|
|
# "slOrdPx": "",
|
|
# "feeCcy": "USDT",
|
|
# "fee": "0.000004",
|
|
# "rebateCcy": "",
|
|
# "source": "",
|
|
# "rebate": "",
|
|
# "category": "normal",
|
|
# "uTime": "1760619119000",
|
|
# "cTime": "1760619119000"
|
|
# }
|
|
#
|
|
# trigger order
|
|
# {
|
|
# "instType": "SPOT",
|
|
# "instId": "DOGE-USDT",
|
|
# "ordId": "1001442305797142",
|
|
# "triggerPx": "0.01",
|
|
# "ordPx": "0.01",
|
|
# "sz": "20",
|
|
# "ordType": "",
|
|
# "side": "buy",
|
|
# "posSide": "",
|
|
# "tdMode": "cash",
|
|
# "triggerOrderType": "Conditional",
|
|
# "triggerPxType": "last",
|
|
# "lever": "",
|
|
# "slPrice": "",
|
|
# "slTriggerPrice": "",
|
|
# "tpPrice": "",
|
|
# "tpTriggerPrice": "",
|
|
# "closeSLTriggerPrice": "",
|
|
# "closeTPTriggerPrice": "",
|
|
# "cTime": "1761814167000",
|
|
# "uTime": "1761814167000"
|
|
# }
|
|
#
|
|
marketId = self.safe_string(order, 'instId')
|
|
market = self.safe_market(marketId, market)
|
|
timestamp = self.safe_integer(order, 'cTime')
|
|
timestampString = self.safe_string(order, 'cTime', '')
|
|
if len(timestampString) < 13:
|
|
timestamp = self.safe_timestamp(order, 'cTime')
|
|
state = self.safe_string(order, 'state')
|
|
orderType = self.safe_string(order, 'ordType')
|
|
average = self.safe_string(order, 'avgPx')
|
|
if average == '':
|
|
average = None
|
|
feeCurrencyId = self.safe_string(order, 'feeCcy')
|
|
fee = None
|
|
if feeCurrencyId is not None:
|
|
feeCost = self.safe_string(order, 'fee')
|
|
fee = {
|
|
'cost': self.parse_number(feeCost),
|
|
'currency': self.safe_currency_code(feeCurrencyId),
|
|
}
|
|
return self.safe_order({
|
|
'id': self.safe_string(order, 'ordId'),
|
|
'clientOrderId': self.safe_string(order, 'clOrdId'),
|
|
'datetime': self.iso8601(timestamp),
|
|
'timestamp': timestamp,
|
|
'lastTradeTimestamp': None,
|
|
'lastUpdateTimestamp': self.safe_integer(order, 'uTime'),
|
|
'status': self.parse_order_status(state),
|
|
'symbol': market['symbol'],
|
|
'type': self.parse_order_type(orderType),
|
|
'timeInForce': self.parse_order_time_in_force(orderType),
|
|
'side': self.safe_string(order, 'side'),
|
|
'price': self.safe_string_2(order, 'px', 'ordPx'),
|
|
'average': average,
|
|
'amount': self.safe_string(order, 'sz'),
|
|
'filled': self.safe_string(order, 'accFillSz'),
|
|
'remaining': None,
|
|
'triggerPrice': self.omit_zero(self.safe_string(order, 'triggerPx')),
|
|
'takeProfitPrice': self.safe_string_2(order, 'tpTriggerPx', 'tpTriggerPrice'),
|
|
'stopLossPrice': self.safe_string_2(order, 'slTriggerPx', 'slTriggerPrice'),
|
|
'cost': None,
|
|
'trades': None,
|
|
'fee': fee,
|
|
'reduceOnly': None,
|
|
'postOnly': (orderType == 'post_only') if orderType else None,
|
|
'info': order,
|
|
}, market)
|
|
|
|
def parse_order_status(self, status: Str) -> Str:
|
|
statuses = {
|
|
'live': 'open',
|
|
'filled': 'closed',
|
|
'canceled': 'canceled',
|
|
'partially_filled': 'open',
|
|
}
|
|
return self.safe_string(statuses, status, status)
|
|
|
|
def parse_order_type(self, type: Str) -> Str:
|
|
types = {
|
|
'limit': 'limit',
|
|
'market': 'market',
|
|
'post_only': 'limit',
|
|
'ioc': 'market',
|
|
'TPSL': 'market',
|
|
}
|
|
return self.safe_string(types, type, type)
|
|
|
|
def parse_order_time_in_force(self, type: Str) -> Str:
|
|
timeInForces = {
|
|
'post_only': 'PO',
|
|
'ioc': 'IOC',
|
|
'limit': 'GTC',
|
|
'market': 'GTC',
|
|
}
|
|
return self.safe_string(timeInForces, type, type)
|
|
|
|
def fetch_positions_for_symbol(self, symbol: str, params={}) -> List[Position]:
|
|
"""
|
|
fetch open positions for a single market
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinAccount/accountPositions
|
|
|
|
fetch all open positions for specific symbol
|
|
:param str symbol: unified market symbol
|
|
: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()
|
|
market = self.market(symbol)
|
|
instrumentType = self.convert_to_instrument_type(market['type'])
|
|
request: dict = {
|
|
'instType': instrumentType,
|
|
'instId': market['id'],
|
|
}
|
|
response = self.privateGetDeepcoinAccountPositions(self.extend(request, params))
|
|
data = self.safe_list(response, 'data', [])
|
|
return self.parse_positions(data, [market['symbol']])
|
|
|
|
def fetch_positions(self, symbols: Strings = None, params={}) -> List[Position]:
|
|
"""
|
|
fetch all open positions
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinAccount/accountPositions
|
|
|
|
: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()
|
|
symbols = self.market_symbols(symbols, None, True, True)
|
|
marketType = 'swap'
|
|
market: Market = None
|
|
if symbols is not None:
|
|
firstSymbol = self.safe_string(symbols, 0)
|
|
market = self.market(firstSymbol)
|
|
marketType, params = self.handle_market_type_and_params('fetchPositions', market, params, marketType)
|
|
instrumentType = self.convert_to_instrument_type(marketType)
|
|
request: dict = {
|
|
'instType': instrumentType,
|
|
}
|
|
response = self.privateGetDeepcoinAccountPositions(self.extend(request, params))
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": [
|
|
# {
|
|
# "instType": "SWAP",
|
|
# "mgnMode": "cross",
|
|
# "instId": "DOGE-USDT-SWAP",
|
|
# "posId": "1001110099878275",
|
|
# "posSide": "long",
|
|
# "pos": "20",
|
|
# "avgPx": "0.18408",
|
|
# "lever": "75",
|
|
# "liqPx": "0.00001",
|
|
# "useMargin": "0.049088",
|
|
# "mrgPosition": "merge",
|
|
# "ccy": "USDT",
|
|
# "uTime": "1760709419000",
|
|
# "cTime": "1760709419000"
|
|
# }
|
|
# ]
|
|
# }
|
|
#
|
|
data = self.safe_list(response, 'data', [])
|
|
return self.parse_positions(data, symbols)
|
|
|
|
def parse_position(self, position: dict, market: Market = None) -> Position:
|
|
#
|
|
# {
|
|
# "instType": "SWAP",
|
|
# "mgnMode": "cross",
|
|
# "instId": "DOGE-USDT-SWAP",
|
|
# "posId": "1001110099878275",
|
|
# "posSide": "long",
|
|
# "pos": "20",
|
|
# "avgPx": "0.18408",
|
|
# "lever": "75",
|
|
# "liqPx": "0.00001",
|
|
# "useMargin": "0.049088",
|
|
# "mrgPosition": "merge",
|
|
# "ccy": "USDT",
|
|
# "uTime": "1760709419000",
|
|
# "cTime": "1760709419000"
|
|
# }
|
|
#
|
|
marketId = self.safe_string(position, 'instId')
|
|
market = self.safe_market(marketId, market)
|
|
timestamp = self.safe_integer(position, 'cTime')
|
|
return self.safe_position({
|
|
'symbol': market['symbol'],
|
|
'id': self.safe_string(position, 'posId'),
|
|
'timestamp': timestamp,
|
|
'datetime': self.iso8601(timestamp),
|
|
'contracts': self.safe_string(position, 'pos'),
|
|
'contractSize': None,
|
|
'side': self.safe_string(position, 'posSide'),
|
|
'notional': None,
|
|
'leverage': self.omit_zero(self.safe_string(position, 'lever')),
|
|
'unrealizedPnl': None,
|
|
'realizedPnl': None,
|
|
'collateral': None,
|
|
'entryPrice': self.safe_string(position, 'avgPx'),
|
|
'markPrice': None,
|
|
'liquidationPrice': self.safe_string(position, 'liqPx'),
|
|
'marginMode': self.safe_string(position, 'mgnMode'),
|
|
'hedged': True,
|
|
'maintenanceMargin': self.safe_string(position, 'useMargin'),
|
|
'maintenanceMarginPercentage': None,
|
|
'initialMargin': None,
|
|
'initialMarginPercentage': None,
|
|
'marginRatio': None,
|
|
'lastUpdateTimestamp': self.safe_integer(position, 'uTime'),
|
|
'lastPrice': None,
|
|
'stopLossPrice': None,
|
|
'takeProfitPrice': None,
|
|
'percentage': None,
|
|
'info': position,
|
|
})
|
|
|
|
def set_leverage(self, leverage: int, symbol: Str = None, params={}):
|
|
"""
|
|
set the level of leverage for a market
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinAccount/accountSetLeverage
|
|
|
|
:param float leverage: the rate of leverage
|
|
:param str symbol: unified market symbol
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param str [params.marginMode]: 'cross' or 'isolated'(default is cross)
|
|
:param str [params.mrgPosition]: 'merge' or 'split', default is merge
|
|
:returns dict: response from the exchange
|
|
"""
|
|
if symbol is None:
|
|
raise ArgumentsRequired(self.id + ' setLeverage() requires a symbol argument')
|
|
# WARNING: THIS WILL INCREASE LIQUIDATION PRICE FOR OPEN ISOLATED LONG POSITIONS
|
|
# AND DECREASE LIQUIDATION PRICE FOR OPEN ISOLATED SHORT POSITIONS
|
|
if leverage < 1:
|
|
raise BadRequest(self.id + ' setLeverage() leverage should be minimum 1')
|
|
self.load_markets()
|
|
market = self.market(symbol)
|
|
marginMode = 'cross'
|
|
marginMode, params = self.handle_margin_mode_and_params('setLeverage', params, marginMode)
|
|
if (marginMode != 'cross') and (marginMode != 'isolated'):
|
|
raise BadRequest(self.id + ' setLeverage() requires a marginMode parameter that must be either cross or isolated')
|
|
mrgPosition = 'merge'
|
|
mrgPosition, params = self.handle_option_and_params(params, 'setLeverage', 'mrgPosition', mrgPosition)
|
|
if mrgPosition != 'merge' and mrgPosition != 'split':
|
|
raise BadRequest(self.id + ' setLeverage() mrgPosition parameter must be either merge or split')
|
|
request: dict = {
|
|
'lever': leverage,
|
|
'mgnMode': marginMode,
|
|
'instId': market['id'],
|
|
'mrgPosition': mrgPosition,
|
|
}
|
|
response = self.privatePostDeepcoinAccountSetLeverage(self.extend(request, params))
|
|
#
|
|
# {
|
|
# code: '0',
|
|
# msg: '',
|
|
# data: {
|
|
# instId: 'ETH-USDT-SWAP',
|
|
# lever: '2',
|
|
# mgnMode: 'cross',
|
|
# mrgPosition: 'merge',
|
|
# sCode: '0',
|
|
# sMsg: ''
|
|
# }
|
|
# }
|
|
#
|
|
return response
|
|
|
|
def fetch_funding_rates(self, symbols: Strings = None, params={}) -> FundingRates:
|
|
"""
|
|
fetch the funding rate for multiple markets
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/currentFundRate
|
|
|
|
:param str[]|None symbols: list of unified market symbols
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param str [params.subType]: "linear" or "inverse"
|
|
: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, 'swap', True, True, True)
|
|
subType = 'linear'
|
|
firstMarket: Market = None
|
|
if symbols is not None:
|
|
firstSymbol = self.safe_string(symbols, 0)
|
|
firstMarket = self.market(firstSymbol)
|
|
subType, params = self.handle_sub_type_and_params('fetchFundingRates', firstMarket, params, subType)
|
|
instType = 'SwapU'
|
|
if subType == 'inverse':
|
|
instType = 'Swap'
|
|
elif subType != 'linear':
|
|
raise BadRequest(self.id + ' fetchFundingRates() subType parameter must be either linear or inverse')
|
|
request: dict = {
|
|
'instType': instType,
|
|
}
|
|
response = self.privateGetDeepcoinTradeFundRateCurrentFundingRate(self.extend(request, params))
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": {
|
|
# "current_fund_rates": [
|
|
# {
|
|
# "instrumentId": "SPKUSDT",
|
|
# "fundingRate": 0.00005
|
|
# },
|
|
# {
|
|
# "instrumentId": "LAUNCHCOINUSDT",
|
|
# "fundingRate": 0.00005
|
|
# }
|
|
# ]
|
|
# }
|
|
# }
|
|
#
|
|
data = self.safe_dict(response, 'data', {})
|
|
rates = self.safe_list(data, 'current_fund_rates', [])
|
|
return self.parse_funding_rates(rates, symbols)
|
|
|
|
def fetch_funding_rate(self, symbol: str, params={}) -> FundingRate:
|
|
"""
|
|
fetch the current funding rate
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/currentFundRate
|
|
|
|
: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)
|
|
if not market['swap']:
|
|
raise ExchangeError(self.id + ' fetchFundingRate() is only valid for swap markets')
|
|
request: dict = {
|
|
'instId': market['id'],
|
|
'instType': self.get_product_group_from_market(market),
|
|
}
|
|
response = self.privateGetDeepcoinTradeFundRateCurrentFundingRate(self.extend(request, params))
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": {
|
|
# "current_fund_rates": [
|
|
# {
|
|
# "instrumentId": "ETHUSDT",
|
|
# "fundingRate": 0.0000402356250176
|
|
# }
|
|
# ]
|
|
# }
|
|
# }
|
|
#
|
|
data = self.safe_dict(response, 'data', {})
|
|
rates = self.safe_list(data, 'current_fund_rates', [])
|
|
entry = self.safe_dict(rates, 0, {})
|
|
return self.parse_funding_rate(entry, market)
|
|
|
|
def parse_funding_rate(self, contract, market: Market = None) -> FundingRate:
|
|
#
|
|
# {
|
|
# "instrumentId": "ETHUSDT",
|
|
# "fundingRate": 0.0000402356250176
|
|
# }
|
|
#
|
|
marketId = self.safe_string_2(contract, 'instrumentId', 'instrumentID')
|
|
symbol = self.safe_symbol(marketId, market)
|
|
return {
|
|
'info': contract,
|
|
'symbol': symbol,
|
|
'markPrice': None,
|
|
'indexPrice': None,
|
|
'interestRate': None,
|
|
'estimatedSettlePrice': None,
|
|
'timestamp': None,
|
|
'datetime': None,
|
|
'fundingRate': self.safe_number(contract, 'fundingRate'),
|
|
'fundingTimestamp': None,
|
|
'fundingDatetime': None,
|
|
'nextFundingRate': None,
|
|
'nextFundingTimestamp': None,
|
|
'nextFundingDatetime': None,
|
|
'previousFundingRate': None,
|
|
'previousFundingTimestamp': None,
|
|
'previousFundingDatetime': None,
|
|
'interval': None,
|
|
}
|
|
|
|
def fetch_funding_rate_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
|
|
"""
|
|
fetches historical funding rate prices
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/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.page]: pagination page number
|
|
:returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
|
|
"""
|
|
if symbol is None:
|
|
raise ArgumentsRequired(self.id + ' fetchFundingRateHistory() requires a symbol argument')
|
|
self.load_markets()
|
|
market = self.market(symbol)
|
|
request: dict = {
|
|
'instId': market['id'],
|
|
}
|
|
if limit is not None:
|
|
request['size'] = limit # default 20, max 100
|
|
response = self.privateGetDeepcoinTradeFundRateHistory(self.extend(request, params))
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": {
|
|
# "rows": [
|
|
# {
|
|
# "instrumentID": "ETHUSD",
|
|
# "rate": "0.00046493",
|
|
# "CreateTime": 1760860800,
|
|
# "ratePeriodSec": 0
|
|
# },
|
|
# {
|
|
# "instrumentID": "ETHUSD",
|
|
# "rate": "0.00047949",
|
|
# "CreateTime": 1760832000,
|
|
# "ratePeriodSec": 0
|
|
# }
|
|
# ]
|
|
# }
|
|
# }
|
|
#
|
|
data = self.safe_dict(response, 'data', {})
|
|
rows = self.safe_list(data, 'rows', [])
|
|
return self.parse_funding_rate_histories(rows, market, since, limit)
|
|
|
|
def parse_funding_rate_history(self, info, market: Market = None):
|
|
#
|
|
# {
|
|
# "instrumentID": "ETHUSD",
|
|
# "rate": "0.00047949",
|
|
# "CreateTime": 1760832000,
|
|
# "ratePeriodSec": 0
|
|
# }
|
|
#
|
|
timestamp = self.safe_timestamp(info, 'CreateTime')
|
|
instrumentID = self.safe_string_2(info, 'instrumentID', 'instrumentId')
|
|
market = self.safe_market(instrumentID, market, None, 'swap')
|
|
return {
|
|
'info': info,
|
|
'symbol': market['symbol'],
|
|
'fundingRate': self.safe_number(info, 'rate'),
|
|
'timestamp': timestamp,
|
|
'datetime': self.iso8601(timestamp),
|
|
}
|
|
|
|
def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
|
|
"""
|
|
fetch all trades made by the user
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/tradeFills
|
|
|
|
:param str symbol: unified market symbol
|
|
:param int [since]: the earliest time in ms to fetch trades for
|
|
:param int [limit]: the maximum number of trades structures to retrieve
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param int [params.until]: timestamp in ms of the latest trade to fetch
|
|
:param str [params.type]: 'spot' or 'swap', the market type for the trades(default is 'spot')
|
|
:param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
|
|
:returns 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_dynamic('fetchMyTrades', symbol, since, limit, params)
|
|
market: Market = None
|
|
if symbol is not None:
|
|
market = self.market(symbol)
|
|
marketType = 'spot'
|
|
marketType, params = self.handle_market_type_and_params('fetchMyTrades', market, params, marketType)
|
|
request: dict = {
|
|
'instType': self.convert_to_instrument_type(marketType),
|
|
}
|
|
if market is not None:
|
|
request['instId'] = market['id']
|
|
if since is not None:
|
|
request['begin'] = since
|
|
if limit is not None:
|
|
request['limit'] = limit # default 100, max 100
|
|
until = self.safe_integer(params, 'until')
|
|
if until is not None:
|
|
params = self.omit(params, 'until')
|
|
request['end'] = until
|
|
response = self.privateGetDeepcoinTradeFills(self.extend(request, params))
|
|
#
|
|
# {
|
|
# "code": "0",
|
|
# "msg": "",
|
|
# "data": [
|
|
# {
|
|
# "instType": "SPOT",
|
|
# "instId": "ETH-USDT",
|
|
# "tradeId": "1001056429613610",
|
|
# "ordId": "1001435238208686",
|
|
# "clOrdId": "",
|
|
# "billId": "10010564296136101",
|
|
# "tag": "",
|
|
# "fillPx": "3791.15",
|
|
# "fillSz": "0.004",
|
|
# "side": "sell",
|
|
# "posSide": "",
|
|
# "execType": "",
|
|
# "feeCcy": "USDT",
|
|
# "fee": "0.0151646",
|
|
# "ts": "1760704540000"
|
|
# }
|
|
# ]
|
|
# }
|
|
#
|
|
data = self.safe_list(response, 'data', [])
|
|
return self.parse_trades(data, market, since, limit)
|
|
|
|
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://www.deepcoin.com/docs/DeepCoinTrade/tradeFills
|
|
|
|
: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
|
|
:param str [params.type]: 'spot' or 'swap', the market type for the trades
|
|
:returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
|
|
"""
|
|
self.load_markets()
|
|
marketType = self.safe_string(params, 'type')
|
|
if symbol is None and marketType is None:
|
|
raise ArgumentsRequired(self.id + ' fetchOrderTrades requires a symbol argument or a market type in the params')
|
|
params = self.extend({'ordId': id}, params)
|
|
return self.fetch_my_trades(symbol, since, limit, params)
|
|
|
|
def close_position(self, symbol: str, side: OrderSide = None, params={}) -> Order:
|
|
"""
|
|
closes open positions for a market
|
|
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/batchClosePosition
|
|
https://www.deepcoin.com/docs/DeepCoinTrade/closePositionByIds
|
|
|
|
:param str symbol: Unified CCXT market symbol
|
|
:param str [side]: not used by deepcoin
|
|
:param dict [params]: extra parameters specific to the exchange API endpoint
|
|
:param str|None [params.positionId]: the id of the position you would like to close
|
|
:param str[]|None [params.positionIds]: list of position ids to close(for batch closing)
|
|
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
|
|
"""
|
|
self.load_markets()
|
|
market = self.market(symbol)
|
|
productGroup = self.get_product_group_from_market(market)
|
|
positionId = self.safe_string(params, 'positionId')
|
|
positionIds = self.safe_list(params, 'positionIds')
|
|
request: dict = {
|
|
'instId': market['id'],
|
|
'productGroup': productGroup,
|
|
}
|
|
response = None
|
|
if positionId is None and positionIds is None:
|
|
response = self.privatePostDeepcoinTradeBatchClosePosition(self.extend(request, params))
|
|
else:
|
|
if positionId is not None:
|
|
params = self.omit(params, 'positionId')
|
|
request['positionIds'] = [positionId]
|
|
response = self.privatePostDeepcoinTradeClosePositionByIds(self.extend(request, params))
|
|
data = self.safe_list(response, 'data', [])
|
|
return self.parse_order(data, market)
|
|
|
|
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
|
|
requestPath = path
|
|
if method == 'GET':
|
|
query = self.urlencode(params)
|
|
if len(query):
|
|
requestPath += '?' + query
|
|
url = self.urls['api'][api] + '/' + requestPath
|
|
if api == 'private':
|
|
self.check_required_credentials()
|
|
timestamp = self.milliseconds()
|
|
dateTime = self.iso8601(timestamp)
|
|
payload = dateTime + method + '/' + requestPath
|
|
headers = {
|
|
'DC-ACCESS-KEY': self.apiKey,
|
|
'DC-ACCESS-TIMESTAMP': dateTime,
|
|
'DC-ACCESS-PASSPHRASE': self.password,
|
|
'appid': '200103',
|
|
}
|
|
if method != 'GET':
|
|
body = self.json(params)
|
|
headers['Content-Type'] = 'application/json'
|
|
payload += body
|
|
signature = self.hmac(self.encode(payload), self.encode(self.secret), hashlib.sha256, 'base64')
|
|
headers['DC-ACCESS-SIGN'] = signature
|
|
return {'url': url, 'method': method, 'body': body, 'headers': headers}
|
|
|
|
def handle_errors(self, code: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
|
|
data = self.safe_dict(response, 'data', {})
|
|
msg = self.safe_string(response, 'msg')
|
|
messageCode = self.safe_string(response, 'code')
|
|
sCode = self.safe_string(data, 'sCode')
|
|
sMsg = self.safe_string(data, 'sMsg')
|
|
errorCode = self.safe_string(data, 'errorCode')
|
|
if (msg is not None) and (msg == '') and (sMsg is not None):
|
|
msg = sMsg
|
|
errorList = self.safe_list(data, 'errorList')
|
|
if errorList is not None:
|
|
for i in range(0, len(errorList)):
|
|
entry = self.safe_dict(errorList, i, {})
|
|
errorCode = self.safe_string(entry, 'errorCode')
|
|
feedback = self.id + ' ' + body
|
|
if (sCode is None) and (errorCode is not None):
|
|
sCode = errorCode
|
|
retCode = self.safe_string(data, 'retCode')
|
|
if (sCode is None) and (retCode is not None):
|
|
sCode = retCode
|
|
if (code != 200) or (messageCode != '0') or (sCode is not None and sCode != '0'):
|
|
self.throw_exactly_matched_exception(self.exceptions['exact'], messageCode, feedback)
|
|
self.throw_exactly_matched_exception(self.exceptions['exact'], sCode, feedback)
|
|
self.throw_exactly_matched_exception(self.exceptions['exact'], msg, feedback)
|
|
self.throw_broadly_matched_exception(self.exceptions['broad'], msg, feedback)
|
|
raise ExchangeError(feedback)
|
|
else:
|
|
list = self.safe_list(data, 'list', [])
|
|
if ('list' in data) and (list is None):
|
|
raise NullResponse(feedback)
|
|
return None
|