KucoinSpotMarketData Class for KuCoin Spot Market Data Retrieval
Source:R/KucoinSpotMarketData.R
KucoinSpotMarketData.RdThe KucoinSpotMarketData class provides an asynchronous interface for retrieving spot market data from KuCoin.
It leverages the coro package for non-blocking HTTP requests, returning promises that resolve to data.table objects
(or character vectors for simple lists). This class supports a comprehensive set of market data endpoints, including
announcements, historical klines, currency details, trading symbols, tickers, trade history, orderbooks, 24-hour stats,
and market lists.
Details
Purpose and Scope
This class is designed to facilitate market analysis and monitoring in the KuCoin Spot trading ecosystem, covering:
Market News: Announcements for updates and events.
Historical Data: Klines for technical analysis.
Asset Metadata: Currency and symbol details for configuration.
Real-Time Data: Tickers, trade history, and orderbooks for live market insights.
Market Overview: 24-hour stats and market lists for broad monitoring.
Usage
Utilised by traders and developers to programmatically access KuCoin Spot market data. The class is initialized with API
credentials (required only for get_full_orderbook), automatically loaded via get_api_keys() if not provided, and a
base URL from get_base_url(). Most endpoints are public, except get_full_orderbook, which requires authentication.
For detailed endpoint information, parameters, and response schemas, refer to the official KuCoin API Documentation.
Methods
initialize(keys, base_url): Initialises the object with API credentials and base URL.
get_announcements(query, page_size, max_pages): Retrieves paginated market announcements.
get_klines(symbol, freq, from, to, concurrent, delay_ms, retries): Fetches historical klines data with segmentation.
get_currency(currency, chain): Retrieves details for a specific currency.
get_all_currencies(): Retrieves details for all available currencies.
get_symbol(symbol): Retrieves details for a specific trading symbol.
get_all_symbols(market): Retrieves all trading symbols, optionally filtered by market.
get_ticker(symbol): Retrieves Level 1 ticker data for a symbol.
get_all_tickers(): Retrieves ticker data for all trading pairs.
get_trade_history(symbol): Retrieves recent trade history for a symbol.
get_part_orderbook(symbol, size): Retrieves partial orderbook data (20 or 100 levels).
get_full_orderbook(symbol): Retrieves full orderbook data (authenticated).
get_24hr_stats(symbol): Retrieves 24-hour market statistics for a symbol.
get_market_list(): Retrieves a list of all trading markets.
Public fields
keysList containing KuCoin API keys (
api_key,api_secret,api_passphrase,key_version).base_urlCharacter string representing the base URL for KuCoin API endpoints. Initialise a New KucoinSpotMarketData Object
Description
Initialises a
KucoinSpotMarketDataobject with API credentials and a base URL for retrieving Spot market data asynchronously. Credentials are only required for authenticated endpoints (e.g.,get_full_orderbook).Workflow Overview
Credential Assignment: Sets
self$keysto the provided or default API keys fromget_api_keys().URL Assignment: Sets
self$base_urlto the provided or default base URL fromget_base_url().
Usage
Creates an instance for accessing KuCoin Spot market data, with most methods being public except where authentication is noted.
Automated Trading Usage
Data Foundation: Use as the primary market data source in your trading bot, feeding real-time and historical data into strategy engines.
Secure Setup: Provide explicit
keysfor authenticated methods or rely onget_api_keys()for portability across environments.Lifecycle: Instantiate once and reuse across trading cycles, pairing with order management classes for a complete system.
Methods
Method new()
Usage
KucoinSpotMarketData$new(keys = get_api_keys(), base_url = get_base_url())Arguments
keysList containing API configuration parameters from
get_api_keys(), including:api_key: Character string; your KuCoin API key.api_secret: Character string; your KuCoin API secret.api_passphrase: Character string; your KuCoin API passphrase.key_version: Character string; API key version (e.g.,"2"). Defaults toget_api_keys().
base_urlCharacter string representing the base URL for the API. Defaults to
get_base_url().
Returns
A new instance of the KucoinSpotMarketData class.
Get Announcements
Description
Retrieves paginated market announcements asynchronously via a GET request to /api/v3/announcements.
Calls get_announcements_impl.
Workflow Overview
Query Setup: Merges defaults with user
query(e.g.,annType = "latest-announcements").Pagination: Fetches pages up to
max_pageswithpage_sizeresults each.Response: Aggregates into a
data.tableof announcement details.
Automated Trading Usage
Event Detection: Filter for
annType = "new-listings"to detect new trading pairs, triggering symbol queries or strategy adjustments.Scheduled Polling: Run hourly with
max_pages = 1to capture recent updates, logging critical announcements (e.g., delistings) for risk management.Alerting: Parse
annDescfor keywords (e.g., "maintenance") to pause trading or notify users via your system’s alerting mechanism.
Method get_announcements()
Usage
KucoinSpotMarketData$get_announcements(
query = list(),
page_size = 50,
max_pages = Inf
)Arguments
queryNamed list; filters for announcements:
annType(character): Type (e.g.,"new-listings","maintenance-updates"). Optional.lang(character): Language (e.g.,"en_US"). Optional.startTime(integer): Start time (ms). Optional.endTime(integer): End time (ms). Optional.
page_sizeInteger; results per page (default 50).
max_pagesNumeric; max pages to fetch (default
Inf).
Returns
Promise resolving to a data.table with:
annId(integer): Announcement ID.annTitle(character): Title.annType(list): Types.annDesc(character): Description.cTime(integer): Release time (ms).language(character): Language.annUrl(character): Full URL.Pagination fields:
currentPage,pageSize,totalNum,totalPage.
JSON Response Example
{"code": "200000", "data": {"items": [{"annId": 123, "annTitle": "New Listing", "annType": ["new-listings"], "annDesc": "BTC-USDT listed", "cTime": 1733049198863, "language": "en_US", "annUrl": "https://kucoin.com/news/123"}]}}Get Klines
Description
Retrieves historical klines (candlestick) data asynchronously via a GET request to /api/v1/market/candes,
segmenting requests to handle the 1500-candle limit. Calls get_klines_impl.
Workflow Overview
Segmentation: Splits time range into segments based on
freqand 1500-candle limit.Fetching: Retrieves segments concurrently or sequentially based on
concurrent.Aggregation: Combines results, removes duplicates, and orders by time.
Automated Trading Usage
Technical Analysis: Fetch daily klines (
freq = "1day") for moving averages or RSI, feeding into strategy signals.Backtesting: Use with large time ranges (e.g., 1 year) and
concurrent = FALSEto build datasets, ensuring rate limit compliance.Real-Time Feed: Set
fromto recent past (e.g., 1 hour ago) and poll frequently, caching results to reduce API load.
Method get_klines()
Arguments
symbolCharacter string; trading pair (e.g., "BTC-USDT"). Required.
freqCharacter string; interval (e.g., "15min"). Options: "1min", "3min", "5min", "15min", "30min", "1hour", "2hour", "4hour", "6hour", "8hour", "12hour", "1day", "1week", "1month". Default "15min".
fromPOSIXct; start time (default 24 hours ago).
toPOSIXct; end time (default now).
concurrentLogical; fetch segments concurrently (default TRUE). Caution: May hit rate limits.
delay_msNumeric; delay between requests (ms, default 0).
retriesInteger; retry attempts per segment (default 3).
Returns
Promise resolving to a data.table with:
datetime(POSIXct): Timestamp.timestamp(numeric): Time (seconds).open(numeric): Opening price.close(numeric): Closing price.high(numeric): High price.low(numeric): Low price.volume(numeric): Volume.turnover(numeric): Turnover.
Description
Retrieves details for a specific currency asynchronously via a GET request to /api/v3/currencies/{currency}.
Calls get_currency_impl.
Workflow Overview
Query: Includes optional
chainparameter.Request: Fetches currency data.
Response: Combines summary and chain-specific details into a
data.table.
Automated Trading Usage
Configuration: Use
precisionto format order sizes correctly in your bot, avoiding rejection.Chain Selection: Specify
chain(e.g., "ERC20") to verify deposit/withdrawal support for multi-chain assets.Validation: Check
isMarginEnabledto enable/disable margin strategies per currency dynamically.
Method get_currency()
Arguments
currencyCharacter string; currency code (e.g., "BTC"). Required.
chainCharacter string; specific chain (e.g., "ERC20"). Optional.
Returns
Promise resolving to a data.table with:
currency(character): Code.name(character): Short name.fullName(character): Full name.precision(integer): Decimals.chainName(character): Blockchain name (if chain-specific).Full schema in implementation docs.
JSON Response Example
{"code": "200000", "data": {"currency": "BTC", "name": "BTC", "fullName": "Bitcoin", "precision": 8, "chains": [{"chainName": "BTC"}]}}Get All Currencies
Description
Retrieves details for all available currencies asynchronously via a GET request to /api/v3/currencies.
Calls get_all_currencies_impl.
Workflow Overview
Request: Fetches all currency data.
Response: Combines summary and chain details into a
data.table.
Automated Trading Usage
Asset Discovery: Fetch periodically to update your system’s supported assets, triggering new trading pair setups.
Fee Planning: Use chain-specific fields (e.g.,
withdrawFeeRate) to calculate transaction costs in strategy logic.Portfolio Check: Filter by
isMarginEnabledto identify margin-eligible assets for leverage strategies.
Method get_all_currencies()
Returns
Promise resolving to a data.table with:
currency(character): Code.name(character): Short name.fullName(character): Full name.precision(integer): Decimals.chainName(character): Blockchain name.Full schema in implementation docs.
JSON Response Example
{"code": "200000", "data": [{"currency": "BTC", "name": "BTC", "fullName": "Bitcoin", "precision": 8, "chains": [{"chainName": "BTC"}]}]}Get Symbol
Description
Retrieves details for a specific trading symbol asynchronously via a GET request to /api/v2/symbols/{symbol}.
Calls get_symbol_impl.
Automated Trading Usage
Order Precision: Use
priceIncrementandbaseIncrementto format orders correctly, ensuring API acceptance.Trading Status: Check
enableTradingto confirm pair availability before placing orders.Fee Adjustment: Apply
makerFeeCoefficientandtakerFeeCoefficientto calculate precise trading costs.
Method get_symbol()
Returns
Promise resolving to a data.table with:
symbol(character): Symbol code.baseCurrency(character): Base currency.quoteCurrency(character): Quote currency.priceIncrement(character): Price step.Full schema in implementation docs.
JSON Response Example
{"code": "200000", "data": {"symbol": "BTC-USDT", "baseCurrency": "BTC", "quoteCurrency": "USDT", "priceIncrement": "0.01"}}Get All Symbols
Description
Retrieves all trading symbols asynchronously via a GET request to /api/v2/symbols, optionally filtered by market.
Calls get_all_symbols_impl.
Workflow Overview
Request: Fetches symbol list with optional
marketfilter.Response: Returns a
data.tableof all symbols.
Automated Trading Usage
Market Scanning: Filter by
market(e.g., "USDS") to identify pairs for specific strategies, updating trading lists dynamically.Pair Validation: Use
baseMinSizeandquoteMaxSizeto enforce order size limits in your bot.Periodic Sync: Run daily to refresh symbol availability, logging new or disabled pairs (
enableTrading).
Method get_all_symbols()
Returns
Promise resolving to a data.table with:
symbol(character): Symbol code.baseCurrency(character): Base currency.quoteCurrency(character): Quote currency.market(character): Market identifier.Full schema in implementation docs.
JSON Response Example
{"code": "200000", "data": [{"symbol": "BTC-USDT", "baseCurrency": "BTC", "quoteCurrency": "USDT", "market": "USDS"}]}Get Ticker
Description
Retrieves Level 1 ticker data asynchronously via a GET request to /api/v1/market/orderbook/level1.
Calls get_ticker_impl.
Workflow Overview
Request: Fetches real-time ticker data for a symbol.
Response: Returns a
data.tablewith bid/ask and last price.
Automated Trading Usage
Price Feed: Poll every few seconds to update live price (
price) and spread (bestAsk - bestBid) for entry/exit decisions.Liquidity Check: Use
bestBidSizeandbestAskSizeto assess market depth before placing large orders.Latency Monitoring: Track
timestamplatency to ensure data freshness, alerting if delays exceed thresholds.
Method get_ticker()
Returns
Promise resolving to a data.table with:
symbol(character): Symbol.timestamp(POSIXct): Snapshot time.time_ms(integer): Time (ms).price(character): Last price.bestBid(character): Best bid.bestAsk(character): Best ask.
JSON Response Example
{"code": "200000", "data": {"time": 1733049198863, "price": "30000", "bestBid": "29990", "bestAsk": "30010"}}Get All Tickers
Description
Retrieves ticker data for all trading pairs asynchronously via a GET request to /api/v1/market/allTickers.
Calls get_all_tickers_impl.
Workflow Overview
Request: Fetches a snapshot of all tickers.
Response: Returns a
data.tablewith market-wide data.
Automated Trading Usage
Market Screening: Filter by
changeRateto identify trending pairs for momentum strategies, updating every minute.Volume Analysis: Use
volValueto prioritize high-liquidity pairs, avoiding low-volume markets.Snapshot Sync: Cache results and compare
globalTime_datetimeto detect API delays or outages.
Method get_all_tickers()
Returns
Promise resolving to a data.table with:
symbol(character): Symbol.buy(character): Best bid.sell(character): Best ask.vol(character): 24-hour volume.globalTime_datetime(POSIXct): Snapshot time.Full schema in implementation docs.
JSON Response Example
{"code": "200000", "data": {"time": 1733049198863, "ticker": [{"symbol": "BTC-USDT", "buy": "29990", "sell": "30010"}]}}Get Trade History
Description
Retrieves the most recent 100 trades for a symbol asynchronously via a GET request to /api/v1/market/histories.
Calls get_trade_history_impl.
Workflow Overview
Request: Fetches recent trade records.
Response: Returns a
data.tablewith trade details.
Automated Trading Usage
Momentum Tracking: Analyze
sideandpricetrends to detect buying/selling pressure, triggering scalping trades.Execution Timing: Use
timestampto measure trade frequency, adjusting order timing in high-frequency strategies.Volume Spike: Sum
sizeover recent trades to spot volume spikes, signaling potential breakouts.
Method get_trade_history()
Returns
Promise resolving to a data.table with:
sequence(character): Trade sequence.price(character): Price.size(character): Amount.side(character): "buy" or "sell".timestamp(POSIXct): Trade time.
JSON Response Example
{"code": "200000", "data": [{"sequence": "123", "price": "30000", "size": "0.1", "side": "buy", "time": 1733049198863000000}]}Get Partial Orderbook
Description
Retrieves partial orderbook data (20 or 100 levels) asynchronously via a GET request to /api/v1/market/orderbook/level2_{size}.
Calls get_part_orderbook_impl.
Workflow Overview
Request: Fetches orderbook snapshot with specified depth.
Response: Returns a
data.tableof bids and asks.
Automated Trading Usage
Liquidity Assessment: Use
sizeatpricelevels to gauge depth for slippage estimation, opting forsize = 100in volatile markets.Spread Trading: Calculate bid-ask spread (
max(bid) - min(ask)) to identify arbitrage opportunities, polling frequently.Order Placement: Adjust limit order prices based on top
pricelevels to compete effectively in the book.
Method get_part_orderbook()
Arguments
symbolCharacter string; trading symbol (e.g., "BTC-USDT"). Required.
sizeInteger; depth (20 or 100, default 20).
Returns
Promise resolving to a data.table with:
timestamp(POSIXct): Snapshot time.sequence(character): Sequence number.side(character): "bid" or "ask".price(character): Price level.size(character): Size at price.
JSON Response Example
{"code": "200000", "data": {"time": 1733049198863, "bids": [["29990", "0.5"]], "asks": [["30010", "0.3"]]}}Get Full Orderbook
Description
Retrieves full orderbook data asynchronously via a GET request to /api/v3/market/orderbook/level2, requiring authentication.
Calls get_full_orderbook_impl.
Workflow Overview
Request: Fetches complete orderbook with authentication.
Response: Returns a
data.tableof all bids and asks.
Automated Trading Usage
Depth Analysis: Aggregate
sizebypriceto assess total liquidity, optimizing large order placement.HFT Strategies: Poll frequently (e.g., every second) with
sequencetracking to detect book changes, enabling rapid arbitrage.Risk Management: Monitor deep levels to anticipate price walls, adjusting stop-loss triggers accordingly.
Method get_full_orderbook()
Returns
Promise resolving to a data.table with:
timestamp(POSIXct): Snapshot time.sequence(character): Sequence number.side(character): "bid" or "ask".price(character): Price level.size(character): Size at price.
JSON Response Example
{"code": "200000", "data": {"time": 1733049198863, "bids": [["29990", "0.5"]], "asks": [["30010", "0.3"]]}}Get 24-Hour Stats
Description
Retrieves 24-hour market statistics asynchronously via a GET request to /api/v1/market/stats.
Calls get_24hr_stats_impl.
Workflow Overview
Request: Fetches 24-hour stats for a symbol.
Response: Returns a
data.tablewith volume and price metrics.
Automated Trading Usage
Volatility Check: Use
changeRateto identify volatile pairs for breakout strategies, polling hourly.Volume Filter: Filter pairs with
volValueabove a threshold for liquidity-focused trading.Trend Confirmation: Compare
lastwithaveragePriceto confirm short-term trends, adjusting positions.
Method get_24hr_stats()
Returns
Promise resolving to a data.table with:
timestamp(POSIXct): Snapshot time.symbol(character): Symbol.buy(character): Best bid.sell(character): Best ask.vol(character): 24-hour volume.Full schema in implementation docs.
JSON Response Example
{"code": "200000", "data": {"time": 1733049198863, "symbol": "BTC-USDT", "vol": "100", "last": "30000"}}Get Market List
Description
Retrieves a list of trading markets asynchronously via a GET request to /api/v1/markets.
Calls get_market_list_impl.
Workflow Overview
Request: Fetches all market identifiers.
Response: Returns a character vector of markets.
Automated Trading Usage
Market Selection: Use as a filter for
get_all_symbolsto focus strategies on specific markets (e.g., "USDS").Portfolio Diversification: Iterate over markets to ensure coverage across asset classes, automating pair selection.
Static Cache: Fetch once daily and cache, as market lists change infrequently, reducing API calls.
Examples
if (FALSE) { # \dontrun{
# Comprehensive example demonstrating key methods
main_async <- coro::async(function() {
# Initialise the class
market <- KucoinSpotMarketData$new()
# Get new listings announcements
announcements <- await(market$get_announcements(list(annType = "new-listings"), page_size = 10, max_pages = 2))
print("New Listings Announcements:"); print(announcements)
# Get 48 hours of hourly klines
klines <- await(market$get_klines("BTC-USDT", "1hour", lubridate::now() - lubridate::dhours(48), lubridate::now()))
print("BTC-USDT Klines:"); print(klines)
# Get ticker data
ticker <- await(market$get_ticker("BTC-USDT"))
print("BTC-USDT Ticker:"); print(ticker)
# Get full orderbook (authenticated)
orderbook <- await(market$get_full_orderbook("BTC-USDT"))
print("BTC-USDT Full Orderbook:"); print(orderbook)
# Get 24-hour stats
stats <- await(market$get_24hr_stats("BTC-USDT"))
print("BTC-USDT 24hr Stats:"); print(stats)
})
main_async()
while (!later::loop_empty()) later::run_now()
} # }