Kucoin REST API#
- class kucoincli.client.BaseClient(api_key=None, api_secret=None, api_passphrase=None, sandbox=False)#
- class kucoincli.client.Client(api_key=None, api_secret=None, api_passphrase=None, sandbox=False, requests_params=None)#
KuCoin REST API wrapper -> https://docs.kucoin.com/#general
- Parameters:
api_key (str) – (Optional) API key generated upon creation of API endpoint on kucoin.com. If no API key is given, the user cannot access functions requiring account level authorization, but can access endpoints that require general auth such as kline historic data.
api_secret (str) – (Optional) Secret API sequence generated upon create of API endpoint on kucoin.com. See api_keydocs for info on optionality of variable
api_passphrase (str) – (Optional) User created API passphrase. Passphrase is created by the user during API setup on kucoin.com. See api_keydocs for info on optionality of variable
sandbox (bool) – If sandbox = True, access a special papertrading API version available for testing trading. For more details visit: https://sandbox.kucoin.com/ Be aware that (1) sandbox API key, secret, and passphrase are NOT the same as regular kucoin API and may only be obtained from the sandbox website and (2) that sandbox markets are completely seperate than kucoin’s regular sites. It is recommended that you not use sandbox as the data is highly corrupted.
- accounts(type: str | None = None, currency: str | None = None, balance: float | None = None, id: str | None = None) DataFrame #
Query API for open accounts filterd by type, currency or balance.
- Parameters:
type (str) – Specify account type to restrict returned accounts to only that type Defaults all account types. Options include: main, margin, trade.
currency (str) – Specify currency (e.g. BTC) to restrict returned accounts to only that currency Defaults to None which returns all currencies.
balance (float) – Specify float value to restrict returns to only accounts with => values.
id (str) – Specify ID# to query an explicit accounts.
- Returns:
Returns pandas dataframe with account details.
- Return type:
DataFrame
- all_tickers(pair: str | None = None, quote: str | None = None) DataFrame #
Query entire market for 24h trading statistics
- Parameters:
pair (str or list or None, optional) – Filter trading pairs by specific currency or list or currencies
quote (str or list or None, optional) – Filter trading currencies by quote currency (right side of trading pair)
- Returns:
Returns pandas DataFrame or Series containing recent trade data for entire market or if pair or quote is specified, a subset of the market.
- Return type:
DataFrame or Series
- construct_socket_path(private=False)#
Construct socketpath from socket detail HTTP request
- create_account(currency: str, type: str) dict #
Create a new sub-account of account type type for currency currency.
- Parameters:
currency (str) – Currency account type to create (e.g., BTC).
type (str) – Type of account to create. Options: main, trade, margin.
- Returns:
JSON dictionary with confirmation message and new account ID.
- Return type:
dict
- debtratio() float #
Pull current cross margin debt ratio as float value
- get_currency_chains(currency)#
Query specific currency for withdrawal information per chain
- Parameters:
currency (str) – Target currency to obtain details (e.g., BTC)
- Returns:
Returns pandas DataFrame with full details for target currency
- Return type:
DataFrame
- get_currency_detail(currency: str | None = None) Series #
Query API for currency or list of currencies including precision and marginability
- Parameters:
currency (str or None, optional) – Target currency to obtain details (e.g. BTC)
- Returns:
Return pandas Series or DataFrame with currency detail
- Return type:
pd.Series or DataFrame
See also
None
,None
- get_fee_rate(currency: str | None = None, type: str = 'crypto') dict #
Get the base fee for users in either crypto or fiat terms
- get_fiat_prices(fiat: str = 'USD', currency=None) Series #
Obtain list of all traded currencies denominated in specified fiat
Useful for comparing prices across pairs with different quote currencies
- Parameters:
fiat (str) – (Optional) Base currency for normalized conversion. Default = USD Options: USD [default], EUR,
currency (str or list) – (Optional) str or list Specific currency or list of currencies to query. If no currency is specified the function will return all traded currencies.
- Returns:
Returns pandas Series containing all currencies or specified list of currencies normalized to the fiat price.
- Return type:
pd.Series
- get_level1_orderbook(pair: str, time='utc') Series #
Obtain best bid-ask spread details for a specified pair
- get_margin_data(currency: str) DataFrame #
Query API for the last 300 fills in the lending and borrowing market
Notes
Response sorted descending on execution time
- Parameters:
currency (str) – Target currency to pull lending/borrowing data (e.g., BTC)
- Returns:
pandas DataFrame containing most recent 300 lending/borrowing rate details
- Return type:
DataFrame
- get_marginable_pairs(base: str | None = None) DataFrame #
Obtain all marginable securities with trade details
- Parameters:
base (None or str or list, optional) – Filter results by base currency. Margin only supported currently for [BTC, ETH, USDT, USDC]
- Returns:
Return DataFrame object with marginable trading pairs and relevant trade details for each pair.
- Return type:
pd.DataFrame
- get_markets() list #
Returns list of markets on KuCoin
- Returns:
Returns list of all KuCoin markets (i.e., NFT)
- Return type:
list
- get_server_time(format: str = 'unix') int #
Return server time in UTC time to millisecond granularity
Notes
This function will return the KuCoin official server time in UTC as unix epoch. Returned time is an integer value representing time to millisecond precision. This function should be used to sync client and server time as orders submitted with a timestamp over 5 seconds old will be rejected by the server. In some cases, client time can lag server time resulting in the server rejected commands as stale.
- Parameters:
format (str, optional) – If format=unix, return the time as UTC Unix-epoch with millisecond accuracy. If format=datetime [default] return a datetime object in UTC time.
- Returns:
Returns time to the millisecond either as a UNIX epoch or datetime object
- Return type:
int or datetime.datetime
- get_socket_detail(private: bool = False) dict #
Get socket details for private or public endpoints
- get_stats(pair: str) Series #
Query API for OHLC(V) figures and assorted statistics on specified pair
- Parameters:
pair (str) – Pair to obtain details for (e.g., BTC-USDT)
- Returns:
Returns pandas Series containing details for target currency
- Return type:
pd.Series
- get_subaccounts(id: str | None = None) dict #
Returns account details for all sub-accounts. Requires Trade authorization
- get_trade_history(pair: str) DataFrame #
Query API for most recent 100 filled trades for target pair
- Parameters:
pair (str) – Target currency pair to query (e.g., BTC-USDT)
- Returns:
Returns pandas Dataframe with filled trade details keyed to timestamp
- Return type:
DataFrame
- lending_rate(currency: str, term: int | None = None) DataFrame #
Query API to obtain current a list of available margin terms
Notes
Sorted descending on sequence of daily interest rate and term
- Parameters:
currency (str) – Target currency to pull lending rates on (e.g., BTC)
- Returns:
Returns pandas DataFrame containing margin rate details
- Return type:
DataFrame
- margin_account(asset: str | None = None, balance: float | None = None) DataFrame #
Return cross margin account details
- Parameters:
asset (None or str or list, optional) – Specify a currency or list of currencies and return only margin account balance information for those assets.
balance (None or float, optional) – Control minimum balance required to include asset in return values.
- Returns:
Returns a DataFrame containing margin account balance details for all available marginable assets
- Return type:
pd.DataFrame or pd.Series
- margin_balance(currency: str | None = None) dict #
Query all outstanding margin balances.
- Parameters:
currency (str) – (Optional) Query specific currency (e.g., BTC). If no currency is specified, query all currencies.
- Returns:
JSON dictionary with margin balance details.
- Return type:
dict
- margin_config() dict #
Pull margin configuration as JSON dictionary
- ohlcv(tickers: str, begin: datetime, end: datetime | None = None, interval: str = '1day', warning: bool = True, ascending=True) DataFrame #
Query historic OHLC(V) data for a ticker or list of tickers
Notes
Server time reported in UTC
- Parameters:
tickers (str or list) – Currency pair or list of pairs. Pair names must be formatted in upper case (e.g. ETH-BTC)
begin (str or datetime.datetime) – Earliest time for queried date range. May be given either as a datetime object or string. String format may include hours/minutes/seconds or may not String format examples: “YYYY-MM-DD” or “YYYY-MM-DD HH:MM:SS”
end (None or str or datetime.datetime, optional) – (Optional) Ending date for queried date range. This parameter has the same formatting rules and flexibility of param begin. If left unspecified, end will default to the current UTC date and time stamp.
interval (str) – Interval at which to return OHLCV data. Interval options: [“1min”, “3min”, “15min”, “30min”, “1hour”, “2hour”, “4hour”, “6hour”, “8hour”, “12hour”, “1day”, “1week”]. Default interval 1day.
progress_bar (bool) – Flag to enable progress bar. Does not work in Jupyter notebooks yet
msg (bool) – Flag for turning on and off helper messages
- Returns:
Returns pandas Dataframe indexed to datetime
- Return type:
DataFrame
- order(symbol: str, side: str, size: float | None = None, funds: float | None = None, type: str = 'market', price: float | None = None, stp: str | None = None, oid: str | None = None, remark: str | None = None, margin: bool = False, mode: str = 'cross', autoborrow: bool = True, tif: str = 'GTC', hidden: bool = False, iceberg: bool = False, visible_size: float | None = None, timeout: int | None = None, postonly: bool = False) dict #
Place limit and market orders using spot trade, cross margin, and isolated margin
- Parameters:
symbol (str) – Specify trading pair for execution (e.g., BTC-USDT)
side (str) – Specify which side of the trade to execute on (i.e., buy or sell)
size (float, optional) – Size in base currency (i.e. the numerator) Quick notes on size: * Size indicates the amount of base currency to buy or sell * Size must be above baseMinSize and below baseMaxSize * Size must be specified in baseIncrement symbol units * Size must be a positive float value
Note: User is required to either specify size or funds.
funds (float, optional) – Amount of funds in quote currency (denominator) to buy or sell. funds is not a valid argument for limit orders. Quick notes on funds parameter: * Funds indicates the amount of price [quote] currency to buy or sell. * Funds must be above quoteMinSize and below quoteMaxSize * Size must be specified in quoteIncrement symbol units * Size must be positive float value
Note: User is required to either specify size or funds.
price (float, optional) – Set specific price at which to buy (sell) the trading pair. Price is only available to limit orders. If price while type=market, the order will be submitted as a limit order.
mode (str, optional) – KuCoin supports both cross [DEFAULT] and isolated margin modes. Please review KuCoin’s account type information for more information.
autoborrow (bool, optional) – Control whether or not the system will automatically borrow funds when executing a margin trade with insufficient real balance. If autoborrow=True [DEFAULT], the exchange will automatically borrow funds at the best interest rate available. If false, users must submit manual borrow orders.
oid (int, optional) – Unique order ID for identification of orders. OID can be set via this argument. If no OID specified, a Unix-time based nonce will be generated and attached to the order.
remark (str, optional) – Add a maximum 100 character UTF-8 remark to the order execution.
stp (str, optional) – [LIMIT ONLY] TP or Self-Trade Prevention parameters. Primarily used by market makers or users who have many multidirectional orders that could trade against each other. STP is not enabled by default. Options for STP: * CN: Cancel newest. If tif=FOK, stp will be forced to CN. * CO: Cancel oldest * CB: Cancel both * DC: Decrease and cancel. Currently not supported for market orders.
tif (str, optional) – [LIMIT ONLY] Add a Time-in-Force policy to the trade execution. If tif unspecified, the default policy is good-to-cancelled. All tif options: * GTC: Good-to-Cancelled. Order will remain on the books till filled or cancelled * GTT: Good-to-Time. Order will remain on books till filled or till
n seconds have passed as specified by timeout argument.
IOC: Immediate or Cancel. IOC orders are filled immediately and not added to the book. Any partial amount that cannot be immediately filled is cancelled.
FOK: Fill or Kill. If entire order cannot be filled at price, the entire order will be rejected.
timeout (int, optional) – Cancel after n seconds. timeout requires Good-to-Time (tif=GTT) policy. If timeout, then tif will be forced to GTT.
postonly (bool, optional) – If postonly is true, orders may only be executed at the maker fee. Orders that would receive taker will be rejected. Postonly is invalid when tif=FOK or IOC.
hidden (bool, optional) – [LIMIT ONLY] Orders will not be visible in the orderbook.
iceberg (bool, optional) – Only a portion of the order will be visible in the orderbook. Use visible_size to control percentage of order size visible.
visible_size (float, optional) – Control % of order visible in orderbook. Note that more than 1/20th of the order must be visible or the order will be rejected. To hide the full order use hidden.
- Returns:
JSON dict with order execution details
- Return type:
dict
- orderbook(pair: str, depth: int = 100, format='df') dict #
Query full or partial orderbook for target pair
Query KuCoin’s orderbook for a specific currency with a variety of depth and format parameters. Note that orderbook historic information cannot be queried.
- Parameters:
pair (str) – Target currency whose orderbook will be obtained (e.g., “BTC-USDT”)
depth (int or str or None, optional) – Specify orderbook depth as integer or as None or full. Be aware that orderbook depths above 100 will require API keys with general privelege or greater. Default = 100.
format (str, optional) – Dictate data structure output. format options include * df and dataframe: Return a formatted dataframe. * raw: Return unaltered dictionary containing full JSON response. Note
that raw only returns exactly the best 100 bid-asks spreads or the entire orderbook. If depth <= 100, format=raw will return the 100 best spreads. If depth > 100 or depth=None or full, the entire orderbook will be returned.
np and numpy: Return a namedtuple with NumPy datastructures. See
Returns
sections for explanation of namedtuple data struct.
- Returns:
format=raw: Return a json dictionary containing either the 100 best bid-ask spreads or the full orderbook. If depth < 100, return the 100 best else return the full orderbook.
format=df or dataframe: Return a pandas DataFrame with multiIndex on rows and columns. Column multiIndex shows Bid and Ask at level 0 and price corresponding to bid-ask price, offer corresponding to total price currency the given price, and value corresponding to total base currency availabe at the given price and offer levels (value= price * offer).
- format=np or numpy: Return a namedtuple containing the following price data:
namedtuple.asset: String value of asset to which the orderbook belongs
namedtuple.time: Unix-epoch time value (at microsecond level)
namedtuple.bids: [N x 2] NumPy array with bid prices in column 0, offer amounts in column 1, and sequence in column 2.
numedtuple.asks: [N x 3] NumPy array with ask prices in column 0, offer amounts in column 1, and sequence in column 2.
- Return type:
dict or DataFrame or namedtuple
Notes
Obtaining depth size greater than 100 or the full orderbook requires API keys with at least general access.
Full orderbook bid-ask depth will almost never be equivalent. This creates NaN values in dataframe returns when format=df or dataframe and depth=None or “full”.
Strict controls are placed on full orderbook API queries and timeouts will be enforced if queried more than 30 times/3s. For a guide on maintaining live orderbooks, see https://docs.kucoin.com/#level-2-market-data.
- Raises:
KucoinResponseError – If HTTP response does not equal 200 or the reponse equals 200, but no data is returned in the JSON object. Common cause of 400 response is invalid API credentials
- recent_orders(page: int = 1, pagesize: int = 50, id: str | None = None) DataFrame #
Returns pandas Series with last 24 hours of trades detailed.
Notes
Max trades per page is 500; Min trades per page is 10
Max number of trades returned (across all pages) is 1000
Data is paganated into n pages displaying pagesize number of trades
- Parameters:
page (int) – (Optional) JSON response is paganated. Use this variable to control the page number viewed. Default value returns first page of paganated data.
pagesize (int) – (Optional) Max number of trades to display per response Default pagesize is 50.
id (str, optional) – Specify an explicit order ID to return values for only that order
- Returns:
Returns pandas DataFrame with complete list of trade details or if a single order ID was specified return a pandas Series with only that trade’s details
- Return type:
DataFrame or Series
- repay_all(currency: str, size: float, priority: str = 'highest') dict #
Function for repaying all outstanding margin debt against specified currency.
- Parameters:
currency (str) – Specific currency to repay liabilities against (e.g., BTC).
size (float) – Total currency sum to repay. Must be a multiple of currency max precision.
priority (str) – (Optional) Specify how to prioritize debt repayment. - Highest: Repay highest interest rate loans first - Soonest: Repay nearest term loans first
- Returns:
Returns JSON dictionary with repayment confirmation and details.
- Return type:
dict
- subusers() DataFrame #
Obtain a list of sub-users
- symbols(pair: str | None = None, market: str | None = None, marginable: str | None = None, quote: str | None = None, base: str | None = None, tradable: str | None = None) DataFrame #
Highly configurable query for detailed list of currency pairs
Primary trading pair detail endpoint for users. This function will return an outline of trading details for all pairs on the KuCoin platform. This function is highly configurable accepting several filtering arguments to return a more focused look at the market.
- Parameters:
currency (str or list or None, optional) – Specify a single pair or list of pairs to query. If currency=None, return all trading pairs
market (str or list or None, optional) – Filter response by trading market. If market=None return all markets. Markets: [‘ALTS’, ‘BTC’, ‘DeFi’, ‘NFT’, ‘USDS’, ‘KCS’, ‘Polkadot’, ‘ETF’, ‘FIAT’]
base (str or list or None, optional) – Specify explicit base currency or list of currencies. If base_curr=None [DEFAULT], all base currencies will be returned.
quote (str or list or None, optional) – Specify explicit quote currency or list of currencies. If base_curr=None [DEFAULT], all quote currencies will be returned.
marginable (bool or None) – If marginable=True, return only marginable securities. If marginable=False return only securities which cannot be traded on margin. If marginable=None [DEFAULT] return all trading pairs regardless of marginability.
tradable (bool or None) – If tradable=True, return trading-enabled securities. If trading=False return untradable listed pairs. If tradable=None [DEFAULT], return all securites regardless of tradability.
- Returns:
Returns pandas DataFrame with with detailed list of all traded pairs. If a list of pairs is provided in the currency parameter, return a DataFrame containing only the specified pairs. If a single pair is provided, return a pandas Series with the pair trade details.
- Return type:
DataFrame or Series
See also
There are several other currency detail endpoints: * .get_currency_detail * .all_tickers * .get_marginable_details
- transfer(currency: str, source_acc: str, dest_acc: str, amount: float, oid: str | None = None) dict #
Function for transferring funds between margin, trade and main accounts.
- Parameters:
currency (str) – Currency to transfer between accounts (e.g., BTC-USDT).
source_acc (str) – Source account type. Options are: Main, trade, and margin.
dest_acc (str) – Destination account type. Options are: Main, trade, and margin.
amount (float) – Positive float value. Must be of the transfer currency precision.
oid (str) – (Optional) Unique order ID for identification of transfer. OID will autogenerate an integer based on the UNIX epoch if not explicitly given.
- Returns:
JSON dictionary with transfer confirmtion and details.
- Return type:
dict