KucoinSubAccount Class for KuCoin Sub-Account Management
Source:R/KucoinSubAccount.R
KucoinSubAccount.Rd
The KucoinSubAccount
class provides an asynchronous interface for managing sub-accounts under a KuCoin master account.
It leverages the coro
package for non-blocking HTTP requests, returning promises that resolve to data.table
objects.
This class supports creating sub-accounts, retrieving summaries and detailed balance information for all sub-accounts,
and fetching comprehensive Spot sub-account balance details across account types.
Details
Purpose and Scope
This class is designed to facilitate sub-account administration within the KuCoin ecosystem, including:
Sub-Account Creation: Adding new sub-accounts with specific permissions.
Summary Overview: Listing all sub-accounts with basic details.
Balance Details: Retrieving financial metrics for individual or all sub-accounts.
Usage
Utilised by traders and developers to programmatically manage KuCoin sub-accounts. The class is initialized with API
credentials, sourced from get_api_keys()
if not provided, and a base URL from get_base_url()
. All methods require
authentication as they operate under the master account’s privileges. 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.
add_subaccount(password, subName, access, remarks): Creates a new sub-account.
get_subaccount_list_summary(page_size, max_pages): Retrieves a paginated summary of all sub-accounts.
get_subaccount_detail_balance(subUserId, includeBaseAmount): Fetches detailed balance for a specific sub-account.
get_subaccount_spot_v2(page_size, max_pages): Retrieves Spot sub-account balance details for all sub-accounts.
Public fields
keys
List containing KuCoin API keys (
api_key
,api_secret
,api_passphrase
,key_version
).base_url
Character string representing the base URL for KuCoin API endpoints. Initialise a New KucoinSubAccount Object
Description
Initialises a
KucoinSubAccount
object with API credentials and a base URL for managing sub-accounts asynchronously. All operations require authentication under the master account’s privileges.Workflow Overview
Credential Assignment: Sets
self$keys
to the provided or default API keys fromget_api_keys()
.URL Assignment: Sets
self$base_url
to the provided or default base URL fromget_base_url()
.
Usage
Creates an instance for sub-account management, enabling creation, summary retrieval, and balance queries.
Automated Trading Usage
Sub-Account Hub: Use as the central object for sub-account operations in your bot, managing trading silos.
Secure Setup: Provide explicit
keys
or useget_api_keys()
from a secure vault for production-grade security.Scalability: Instantiate once and reuse across sessions, integrating with account and funding classes for comprehensive oversight.
Methods
Method new()
Usage
KucoinSubAccount$new(keys = get_api_keys(), base_url = get_base_url())
Arguments
keys
List 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_url
Character string representing the base URL for the API. Defaults to
get_base_url()
.
Returns
A new instance of the KucoinSubAccount
class.
Add Sub-Account
Description
Creates a new sub-account under the master account asynchronously via a POST request to /api/v2/sub/user/created
.
Calls add_subaccount_impl
.
Workflow Overview
Validation: Ensures parameters meet API constraints within the implementation.
Request Body: Constructs JSON with
password
,subName
,access
, and optionalremarks
.Authentication: Generates headers with API keys.
API Call: Sends POST request.
Response: Returns sub-account details as a
data.table
.
Usage
Utilised to create sub-accounts with specific permissions for segregated trading or management purposes.
Automated Trading Usage
Account Segregation: Create sub-accounts with
access = "Spot"
for isolated trading strategies, assigning uniquesubName
s for tracking.Security: Use strong, unique
password
s generated programmatically, storing securely withremarks
for audit trails.Post-Creation: Follow with
get_subaccount_list_summary
to verify creation and retrieveuid
for further operations.
Method add_subaccount()
Arguments
password
Character string; sub-account password (7-24 characters, must include letters and numbers). Required.
subName
Character string; sub-account name (7-32 characters, must include a letter and number, no spaces). Required.
access
Character string; permission type ("Spot", "Futures", "Margin"). Required.
remarks
Character string; optional remarks (1-24 characters if provided).
Returns
Promise resolving to a data.table
with:
uid
(integer): Sub-account ID.subName
(character): Sub-account name.remarks
(character): Remarks (if provided).access
(character): Permission type.
JSON Response Example
{"code": "200000", "data": {"uid": 169579801, "subName": "TestSub123", "remarks": "Test", "access": "Spot"}}
Get Sub-Account List Summary
Description
Retrieves a paginated summary of all sub-accounts asynchronously via a GET request to /api/v2/sub/user
.
Calls get_subaccount_list_summary_impl
.
Workflow Overview
Pagination: Fetches pages with
page_size
up tomax_pages
.Request: Constructs authenticated GET request.
Response: Aggregates results into a
data.table
with datetime conversion.
Usage
Utilised to obtain an overview of all sub-accounts, including creation details and permissions.
Automated Trading Usage
Inventory Management: Fetch periodically to maintain an updated sub-account list, using
uid
for balance queries.Permission Audit: Check
access
to ensure sub-accounts align with intended trading scopes, alerting on mismatches.Creation Tracking: Use
createdDatetime
to monitor sub-account age, flagging old accounts for review or cleanup.
Method get_subaccount_list_summary()
Arguments
page_size
Integer; results per page (1-100, default 100).
max_pages
Numeric; max pages to fetch (default
Inf
).
Returns
Promise resolving to a data.table
with:
uid
(integer): Sub-account ID.subName
(character): Sub-account name.access
(character): Permission type.createdDatetime
(POSIXct): Creation time.Full schema in implementation docs.
JSON Response Example
{"code": "200000", "data": {"items": [{"uid": 169579801, "subName": "TestSub123", "access": "Spot", "createdAt": 1668562696000}]}}
Get Sub-Account Detail Balance
Description
Retrieves detailed balance information for a specific sub-account asynchronously via a GET request to /api/v1/sub-accounts/{subUserId}
.
Calls get_subaccount_detail_balance_impl
.
Workflow Overview
Request: Constructs authenticated GET request with
subUserId
andincludeBaseAmount
.Response: Aggregates balances across account types into a
data.table
.
API Endpoint
GET https://api.kucoin.com/api/v1/sub-accounts/{subUserId}?includeBaseAmount={includeBaseAmount}
Usage
Utilised to monitor financial details for a specific sub-account across various account types.
Automated Trading Usage
Fund Monitoring: Check
available
peraccountType
to manage sub-account liquidity, triggering transfers if low.Zero Balance Inclusion: Set
includeBaseAmount = TRUE
to audit unused currencies, initializing them as needed.Sub-Account Focus: Use
subUserId
fromget_subaccount_list_summary
to drill down into critical accounts, logging balances.
Method get_subaccount_detail_balance()
Arguments
subUserId
Character string; sub-account user ID (e.g., from
get_subaccount_list_summary
). Required.includeBaseAmount
Logical; include zero-balance currencies (default
FALSE
).
Returns
Promise resolving to a data.table
with:
subUserId
(character): Sub-account ID.subName
(character): Sub-account name.accountType
(character): Account type (e.g., "mainAccounts").currency
(character): Currency code.balance
(numeric): Total balance.Full schema in implementation docs.
JSON Response Example
{"code": "200000", "data": {"subUserId": "123", "subName": "TestSub", "mainAccounts": [{"currency": "USDT", "balance": "0.01"}]}}
Get Spot Sub-Account List (V2)
Description
Retrieves paginated Spot sub-account balance details for all sub-accounts asynchronously via a GET request to /api/v2/sub-accounts
.
Calls get_subaccount_spot_v2_impl
.
Workflow Overview
Pagination: Fetches pages with
page_size
up tomax_pages
.Request: Constructs authenticated GET request.
Response: Aggregates balances across account types into a
data.table
.
Automated Trading Usage
Portfolio Overview: Aggregate
balance
acrosssubUserId
andaccountType
to monitor total sub-account funds, reallocating as needed.Risk Assessment: Filter by
holds
to identify locked funds, adjusting trading limits per sub-account.Batch Processing: Use with small
page_size
for frequent updates, caching results to reduce API load.
Method get_subaccount_spot_v2()
Arguments
page_size
Integer; results per page (10-100, default 100).
max_pages
Numeric; max pages to fetch (default
Inf
).
Examples
if (FALSE) { # \dontrun{
# Comprehensive example demonstrating key methods
main_async <- coro::async(function() {
# Initialise the class
sub_acc <- KucoinSubAccount$new()
# Add a new sub-account
new_sub <- await(sub_acc$add_subaccount(
password = "SecurePass123",
subName = "TradingSub1",
access = "Spot",
remarks = "Spot trading sub-account"
))
print("New Sub-Account:"); print(new_sub)
# Get sub-account summary
summary <- await(sub_acc$get_subaccount_list_summary(page_size = 10, max_pages = 1))
print("Sub-Account Summary:"); print(summary)
# Get balance for the new sub-account (if created)
if (nrow(summary) > 0) {
sub_id <- summary[1, uid]
balance <- await(sub_acc$get_subaccount_detail_balance(sub_id, includeBaseAmount = TRUE))
print("Sub-Account Balance:"); print(balance)
}
# Get Spot sub-account balances
spot_balances <- await(sub_acc$get_subaccount_spot_v2(page_size = 20, max_pages = 2))
print("Spot Sub-Account Balances:"); print(spot_balances)
})
main_async()
while (!later::loop_empty()) later::run_now()
} # }