diff --git a/R/KucoinAccountAndFunding.R b/R/KucoinAccountAndFunding.R index f1a9fa19..dc2734bb 100644 --- a/R/KucoinAccountAndFunding.R +++ b/R/KucoinAccountAndFunding.R @@ -1,140 +1,126 @@ # File: ./R/KucoinAccountAndFunding.R -# box::use( -# impl = ./impl_account_account_and_funding, -# ./utils[ get_api_keys, get_base_url ] -# ) +box::use( + ./impl_account_account_and_funding[ + get_account_summary_info_impl, + get_apikey_info_impl, + get_spot_account_type_impl, + get_spot_account_list_impl, + get_spot_account_detail_impl, + get_cross_margin_account_impl, + get_isolated_margin_account_impl, + get_spot_ledger_impl + ], + ./utils[get_api_keys, get_base_url] +) -#' KucoinAccountAndFunding Class for KuCoin Account & Funding Endpoints +#' KucoinAccountAndFunding Class for KuCoin Account and Funding Management #' -#' The `KucoinAccountAndFunding` class provides a comprehensive, asynchronous interface for interacting with the -#' Account & Funding endpoints of the KuCoin API. It leverages the `coro` package to perform non-blocking HTTP requests -#' and returns promises that often resolve to `data.table` objects. This class covers a wide range of functionalities, -#' including: +#' The `KucoinAccountAndFunding` class provides a comprehensive, asynchronous interface for managing account and funding +#' operations on KuCoin. It leverages the `coro` package for non-blocking HTTP requests, returning promises that resolve +#' to `data.table` objects or logical values. This class encompasses a wide range of functionalities, including account +#' summaries, API key details, spot account types, account lists, and ledger records for spot and margin accounts. #' -#' - Retrieving a complete account summary (VIP level, sub-account counts, and various limits). -#' - Fetching detailed API key information (key details, permissions, IP whitelist, creation time, etc.). -#' - Determining the type of your spot account (high-frequency vs. low-frequency). -#' - Listing all spot accounts, with optional filters for currency and account type. -#' - Obtaining detailed information for a specific spot account. -#' - Retrieving cross margin account information with asset/liability summaries. -#' - Fetching isolated margin account data for specific trading pairs. -#' - Obtaining detailed ledger records (transaction histories) for spot and margin accounts. +#' ### Purpose and Scope +#' This class is designed to manage and monitor KuCoin account details and funding activities, covering: +#' - **Account Overview**: Summaries of VIP levels, sub-accounts, and limits. +#' - **API Key Insights**: Metadata and permissions of the API key. +#' - **Spot Account Management**: Type detection, account lists, and detailed financial metrics. +#' - **Margin Accounts**: Cross and isolated margin account details. +#' - **Transaction History**: Ledger records for tracking funding activities. #' #' ### Workflow Overview #' Not applicable (class definition overview). #' #' ### API Endpoint -#' Not applicable (class-level documentation; see individual methods). +#' Not applicable (class-level documentation; see individual methods for specific endpoints). #' #' ### Usage -#' Utilised by users to interact with KuCoin's Account & Funding endpoints. The class is initialised with API credentials, -#' automatically loaded via `get_api_keys()` if not provided, and a base URL from `get_base_url()`. For detailed endpoint -#' information and response schemas, refer to the official [KuCoin API Documentation](https://www.kucoin.com/docs-new). +#' Utilised by traders and developers to programmatically interact with KuCoin’s Account & Funding endpoints. 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. For detailed endpoint information, parameters, and response schemas, refer to the +#' official [KuCoin API Documentation](https://www.kucoin.com/docs-new). #' #' ### Official Documentation -#' [KuCoin API Documentation](https://www.kucoin.com/docs-new) +#' [KuCoin API Documentation - Account & Funding](https://www.kucoin.com/docs-new/rest/account-info/account-funding/introduction) #' #' @section Methods: -#' - **initialize(keys, base_url):** Initialises the object with API credentials and the base URL. -#' - **get_account_summary_info():** Retrieves a comprehensive summary of the user's account. -#' - **get_apikey_info():** Retrieves detailed information about the API key. -#' - **get_spot_account_type():** Determines whether the spot account is high-frequency or low-frequency. -#' - **get_spot_account_list(query):** Retrieves a list of all spot accounts with optional filters. -#' - **get_spot_account_detail(accountId):** Retrieves detailed information for a specific spot account. -#' - **get_cross_margin_account(query):** Retrieves cross margin account information based on specified filters. -#' - **get_isolated_margin_account(query):** Retrieves isolated margin account data for specific trading pairs. -#' - **get_spot_ledger(query, page_size, max_pages):** Retrieves detailed ledger records for spot and margin accounts, including pagination. +#' - **initialize(keys, base_url):** Initialises the object with API credentials and base URL. +#' - **get_account_summary_info():** Retrieves a summary of account status and limits. +#' - **get_apikey_info():** Fetches detailed API key metadata. +#' - **get_spot_account_type():** Determines if the spot account is high-frequency. +#' - **get_spot_account_list(query):** Lists all spot accounts with optional filters. +#' - **get_spot_account_detail(accountId):** Retrieves details for a specific spot account. +#' - **get_cross_margin_account(query):** Fetches cross margin account information. +#' - **get_isolated_margin_account(query):** Retrieves isolated margin account details. +#' - **get_spot_ledger(query, page_size, max_pages):** Fetches paginated ledger records. #' #' @return Not applicable (class definition; see individual methods for return values). #' #' @examples #' \dontrun{ +#' # Comprehensive example demonstrating key methods #' main_async <- coro::async(function() { #' # Initialise the class #' account <- KucoinAccountAndFunding$new() #' #' # Get account summary #' summary <- await(account$get_account_summary_info()) -#' print("Account Summary:") -#' print(summary) -#' -#' # Get API key info -#' key_info <- await(account$get_apikey_info()) -#' print("API Key Info:") -#' print(key_info) +#' print("Account Summary:"); print(summary) #' #' # Check spot account type #' is_high_freq <- await(account$get_spot_account_type()) -#' cat("Spot Account High-Frequency:", is_high_freq, "\n") -#' -#' # List spot accounts and filter for USDT main accounts -#' spot_accounts <- await(account$get_spot_account_list(list(currency = "USDT", type = "main"))) -#' print("Spot Accounts (USDT Main):") -#' print(spot_accounts) +#' cat("Is High-Frequency Spot Account:", is_high_freq, "\n") #' -#' # Get details for the first USDT main account (if any) -#' if (nrow(spot_accounts) > 0) { -#' account_id <- spot_accounts[1, id] -#' account_detail <- await(account$get_spot_account_detail(account_id)) -#' print("Spot Account Detail:") -#' print(account_detail) -#' } +#' # List USDT trade accounts +#' spot_accounts <- await(account$get_spot_account_list(list(currency = "USDT", type = "trade"))) +#' print("USDT Trade Accounts:"); print(spot_accounts) #' -#' # Get cross margin account info -#' cross_margin <- await(account$get_cross_margin_account(list(quoteCurrency = "USDT"))) -#' print("Cross Margin Summary:") -#' print(cross_margin$summary) -#' print("Cross Margin Accounts:") -#' print(cross_margin$accounts) -#' -#' # Get isolated margin account info for BTC-USDT -#' isolated_margin <- await(account$get_isolated_margin_account(list(symbol = "BTC-USDT"))) -#' print("Isolated Margin Summary:") -#' print(isolated_margin$summary) -#' print("Isolated Margin Assets:") -#' print(isolated_margin$assets) -#' -#' # Get spot ledger records for BTC transfers in the last day -#' query <- list(currency = "BTC", bizType = "TRANSFER", startAt = as.integer(Sys.time() - 86400) * 1000, endAt = as.integer(Sys.time()) * 1000) -#' ledger <- await(account$get_spot_ledger(query, page_size = 50, max_pages = 2)) -#' print("Spot Ledger Records:") -#' print(ledger) +#' # Get ledger for last 24 hours +#' ledger <- await(account$get_spot_ledger( +#' list(currency = "BTC", startAt = as.integer(Sys.time() - 24*3600) * 1000), +#' page_size = 20, +#' max_pages = 1 +#' )) +#' print("Recent BTC Ledger:"); print(ledger) #' }) #' main_async() #' while (!later::loop_empty()) later::run_now() #' } #' #' @importFrom R6 R6Class -#' @importFrom coro async -#' @importFrom data.table data.table #' @export KucoinAccountAndFunding <- R6::R6Class( "KucoinAccountAndFunding", public = list( - #' @field keys List of API configuration parameters from `get_api_keys()`, including `api_key`, `api_secret`, - #' `api_passphrase`, and `key_version`. + #' @field keys List containing KuCoin API keys (`api_key`, `api_secret`, `api_passphrase`, `key_version`). keys = NULL, - #' @field base_url Character string representing the base URL for the KuCoin API, obtained via `get_base_url()`. + #' @field base_url Character string representing the base URL for KuCoin API endpoints. base_url = NULL, #' Initialise a New KucoinAccountAndFunding Object #' #' ### Description - #' Initialises a `KucoinAccountAndFunding` object with API credentials and a base URL for interacting with KuCoin's Account & Funding endpoints asynchronously. If credentials or the base URL are not provided, they are sourced from `get_api_keys()` and `get_base_url()`, respectively. + #' Initialises a `KucoinAccountAndFunding` object with API credentials and a base URL for managing account and + #' funding operations asynchronously. All methods require authentication via API keys. #' #' ### Workflow Overview - #' 1. **Credential Assignment**: Assigns the provided or default API keys to `self$keys`. - #' 2. **URL Assignment**: Assigns the provided or default base URL to `self$base_url`. + #' 1. **Credential Assignment**: Sets `self$keys` to the provided or default API keys from `get_api_keys()`. + #' 2. **URL Assignment**: Sets `self$base_url` to the provided or default base URL from `get_base_url()`. #' #' ### API Endpoint #' Not applicable (initialisation method). #' #' ### Usage - #' Utilised to create an instance of the class with necessary authentication details for accessing KuCoin API endpoints. + #' Creates an instance for accessing KuCoin account and funding data, requiring authenticated API access. #' #' ### Official Documentation - #' [KuCoin API Authentication](https://www.kucoin.com/docs-new/rest/introduction) + #' [KuCoin API Authentication](https://www.kucoin.com/docs-new/rest/introduction#authentication) + #' + #' ### Automated Trading Usage + #' - **Account Hub**: Use as the central object for account monitoring in your bot, integrating with trading strategies. + #' - **Secure Setup**: Provide explicit `keys` or use `get_api_keys()` from a secure source for production safety. + #' - **Lifecycle Management**: Instantiate once and reuse across sessions, pairing with deposit/withdrawal classes for full financial oversight. #' #' @param keys List containing API configuration parameters from `get_api_keys()`, including: #' - `api_key`: Character string; your KuCoin API key. @@ -150,313 +136,332 @@ KucoinAccountAndFunding <- R6::R6Class( self$base_url <- base_url }, - #' Retrieve Account Summary Information + #' Get Account Summary Information #' #' ### Description - #' Retrieves a comprehensive summary of the user's account from the KuCoin API asynchronously. This includes the VIP level, total number of sub-accounts, breakdown by trading type (spot, margin, futures, options), and associated limits. This method calls the internal `get_account_summary_info_impl` function. + #' Retrieves a comprehensive account summary asynchronously via a GET request to `/api/v2/user-info`. + #' Calls `get_account_summary_info_impl`. #' #' ### Workflow Overview - #' 1. **URL Construction**: Combines the base URL with the endpoint `/api/v2/user-info`. - #' 2. **Header Preparation**: Constructs authentication headers using `build_headers()` with the HTTP method, endpoint, and an empty request body. - #' 3. **API Request**: Sends a GET request with a 3-second timeout via `httr::GET()`. - #' 4. **Response Processing**: Processes the JSON response with `process_kucoin_response()`, converting the `"data"` field into a `data.table`. + #' 1. **Request**: Constructs authenticated GET request. + #' 2. **Response**: Returns a `data.table` with VIP level, sub-account counts, and limits. #' #' ### API Endpoint #' `GET https://api.kucoin.com/api/v2/user-info` #' #' ### Usage - #' Utilised by users to obtain a high-level overview of their KuCoin account status, including sub-account limits and VIP tier benefits. + #' Utilised to obtain a high-level overview of account status, including sub-account limits and VIP benefits. #' #' ### Official Documentation #' [KuCoin Get Account Summary Info](https://www.kucoin.com/docs-new/rest/account-info/account-funding/get-account-summary-info) #' - #' @return Promise resolving to a `data.table` containing: - #' - `level` (integer): User's VIP level. - #' - `subQuantity` (integer): Total number of sub-accounts. - #' - `spotSubQuantity` (integer): Number of spot trading sub-accounts. - #' - `marginSubQuantity` (integer): Number of margin trading sub-accounts. - #' - `futuresSubQuantity` (integer): Number of futures trading sub-accounts. - #' - `optionSubQuantity` (integer): Number of option trading sub-accounts. - #' - `maxSubQuantity` (integer): Maximum allowed sub-accounts (sum of `maxDefaultSubQuantity` and `maxSpotSubQuantity`). - #' - `maxDefaultSubQuantity` (integer): Maximum default sub-accounts based on VIP level. - #' - `maxSpotSubQuantity` (integer): Maximum additional spot sub-accounts. - #' - `maxMarginSubQuantity` (integer): Maximum additional margin sub-accounts. - #' - `maxFuturesSubQuantity` (integer): Maximum additional futures sub-accounts. - #' - `maxOptionSubQuantity` (integer): Maximum additional option sub-accounts. + #' ### Automated Trading Usage + #' - **Capacity Check**: Monitor `maxSubQuantity` to manage sub-account creation, scaling bot operations as needed. + #' - **VIP Benefits**: Adjust trading fees or limits in your bot based on `level`, optimizing cost strategies. + #' - **Periodic Audit**: Fetch daily to log account health, alerting if sub-account limits are near capacity. + #' + #' @return Promise resolving to a `data.table` with: + #' - `level` (integer): VIP level. + #' - `subQuantity` (integer): Total sub-accounts. + #' - `spotSubQuantity` (integer): Spot sub-accounts. + #' - `maxSubQuantity` (integer): Max allowed sub-accounts. + #' - Full schema in implementation docs. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": {"level": 3, "subQuantity": 5, "maxSubQuantity": 20}} + #' ``` get_account_summary_info = function() { return(get_account_summary_info_impl(self$keys, self$base_url)) }, - #' Retrieve API Key Information + #' Get API Key Information #' #' ### Description - #' Retrieves detailed metadata about the API key used for authentication from the KuCoin API asynchronously. This includes account UID, sub-account name (if applicable), remarks, permissions, IP whitelist, and creation timestamp. This method calls `get_apikey_info_impl`. + #' Retrieves detailed API key metadata asynchronously via a GET request to `/api/v1/user/api-key`. + #' Calls `get_apikey_info_impl`. #' #' ### Workflow Overview - #' 1. **URL Construction**: Combines the base URL with the endpoint `/api/v1/user/api-key`. - #' 2. **Header Preparation**: Constructs authentication headers using `build_headers()`. - #' 3. **API Request**: Sends a GET request with a 3-second timeout via `httr::GET()`. - #' 4. **Response Processing**: Processes the response with `process_kucoin_response()`, converting the `"data"` field into a `data.table`. + #' 1. **Request**: Constructs authenticated GET request. + #' 2. **Response**: Returns a `data.table` with key details and permissions. #' #' ### API Endpoint #' `GET https://api.kucoin.com/api/v1/user/api-key` #' #' ### Usage - #' Utilised by users to inspect the properties and permissions of their KuCoin API key, aiding in security and configuration audits. + #' Utilised to inspect API key properties, aiding in security and permission audits. #' #' ### Official Documentation #' [KuCoin Get API Key Info](https://www.kucoin.com/docs-new/rest/account-info/account-funding/get-apikey-info) #' - #' @return Promise resolving to a `data.table` containing: + #' ### Automated Trading Usage + #' - **Permission Sync**: Verify `permission` includes required scopes (e.g., "Spot") before bot operations, halting if insufficient. + #' - **Security Audit**: Check `ipWhitelist` and `createdAt` to enforce IP restrictions or key rotation policies. + #' - **Logging**: Log `uid` and `subName` to map API keys to accounts, ensuring traceability in multi-user systems. + #' + #' @return Promise resolving to a `data.table` with: #' - `uid` (integer): Account UID. - #' - `subName` (character, optional): Sub-account name (if applicable). - #' - `remark` (character): API key remarks. #' - `apiKey` (character): API key string. - #' - `apiVersion` (integer): API version. - #' - `permission` (character): Comma-separated permissions list (e.g., `"General, Spot"`). - #' - `ipWhitelist` (character, optional): IP whitelist. - #' - `isMaster` (logical): Master account indicator. - #' - `createdAt` (integer): Creation timestamp in milliseconds. + #' - `permission` (character): Permissions list. + #' - `createdAt` (integer): Creation time (ms). + #' - Full schema in implementation docs. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": {"uid": 12345, "apiKey": "abc123", "permission": "General, Spot", "createdAt": 1733049198863}} + #' ``` get_apikey_info = function() { return(get_apikey_info_impl(self$keys, self$base_url)) }, - #' Determine Spot Account Type + #' Get Spot Account Type #' #' ### Description - #' Determines whether the user's spot account is high-frequency or low-frequency asynchronously. This distinction affects asset transfer and balance query endpoints. This method calls `get_spot_account_type_impl`. + #' Determines if the spot account is high-frequency asynchronously via a GET request to `/api/v1/hf/accounts/opened`. + #' Calls `get_spot_account_type_impl`. #' #' ### Workflow Overview - #' 1. **URL Construction**: Combines the base URL with `/api/v1/hf/accounts/opened`. - #' 2. **Header Preparation**: Constructs authentication headers via `build_headers()`. - #' 3. **API Request**: Sends a GET request with a 3-second timeout via `httr::GET()`. - #' 4. **Response Processing**: Extracts the boolean `"data"` field from the response processed by `process_kucoin_response()`. + #' 1. **Request**: Constructs authenticated GET request. + #' 2. **Response**: Returns a logical indicating high-frequency status. #' #' ### API Endpoint #' `GET https://api.kucoin.com/api/v1/hf/accounts/opened` #' #' ### Usage - #' Utilised by users to identify their spot account type, which influences the appropriate endpoints for trading operations. + #' Utilised to identify spot account type, affecting endpoint usage for trading operations. #' #' ### Official Documentation #' [KuCoin Get Account Type Spot](https://www.kucoin.com/docs-new/rest/account-info/account-funding/get-account-type-spot) #' - #' @return Promise resolving to a logical value: + #' ### Automated Trading Usage + #' - **Endpoint Selection**: Use result to choose between high-frequency (HF) or low-frequency endpoints for orders and transfers. + #' - **Performance Tuning**: Adjust polling frequency in your bot based on account type, optimizing for HF accounts. + #' - **Initial Check**: Run at bot startup to configure workflows, logging the type for debugging. + #' + #' @return Promise resolving to a logical: #' - `TRUE`: High-frequency spot account. #' - `FALSE`: Low-frequency spot account. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": true} + #' ``` get_spot_account_type = function() { return(get_spot_account_type_impl(self$keys, self$base_url)) }, - #' Retrieve Spot Account List + #' Get Spot Account List #' #' ### Description - #' Retrieves a list of all spot accounts associated with the KuCoin account asynchronously, with optional filters for currency and account type. This method returns financial metrics in a `data.table` and calls `get_spot_account_list_impl`. + #' Retrieves a list of all spot accounts asynchronously via a GET request to `/api/v1/accounts`. + #' Calls `get_spot_account_list_impl`. #' #' ### Workflow Overview - #' 1. **URL Construction**: Combines the base URL with `/api/v1/accounts` and a query string from `build_query()`. - #' 2. **Header Preparation**: Constructs authentication headers using `build_headers()`. - #' 3. **API Request**: Sends a GET request with a 3-second timeout via `httr::GET()`. - #' 4. **Response Processing**: Converts the `"data"` array into a `data.table`, handling empty responses with a typed empty table. + #' 1. **Query**: Applies optional filters from `query`. + #' 2. **Request**: Constructs authenticated GET request. + #' 3. **Response**: Returns a `data.table` of account details. #' #' ### API Endpoint #' `GET https://api.kucoin.com/api/v1/accounts` #' #' ### Usage - #' Utilised by users to list all spot accounts, filterable by currency or type, for account management or monitoring. + #' Utilised to list spot accounts, filterable by currency or type, for financial monitoring. #' #' ### Official Documentation #' [KuCoin Get Account List Spot](https://www.kucoin.com/docs-new/rest/account-info/account-funding/get-account-list-spot) #' - #' @param query Named list of query parameters, e.g., `list(currency = "USDT", type = "main")`. Supported: - #' - `currency` (character, optional): Filter by currency (e.g., `"USDT"`). - #' - `type` (character, optional): Filter by account type (`"main"`, `"trade"`). + #' ### Automated Trading Usage + #' - **Fund Allocation**: Filter by `type = "trade"` to monitor trading funds, reallocating via transfers if `available` is low. + #' - **Currency Tracking**: Use `currency` filter to manage specific asset balances, integrating with market data. + #' - **Real-Time Sync**: Poll periodically to update account states, caching IDs for detailed queries. #' - #' @return Promise resolving to a `data.table` containing: + #' @param query Named list; optional filters: + #' - `currency` (character): Currency code (e.g., "USDT"). + #' - `type` (character): Account type ("main", "trade"). + #' @return Promise resolving to a `data.table` with: #' - `id` (character): Account ID. #' - `currency` (character): Currency code. - #' - `type` (character): Account type (e.g., `"main"`, `"trade"`). + #' - `type` (character): Account type. #' - `balance` (numeric): Total funds. #' - `available` (numeric): Available funds. #' - `holds` (numeric): Funds on hold. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": [{"id": "123", "currency": "USDT", "type": "trade", "balance": "1000", "available": "900", "holds": "100"}]} + #' ``` get_spot_account_list = function(query = list()) { return(get_spot_account_list_impl(self$keys, self$base_url, query)) }, - #' Retrieve Spot Account Details + #' Get Spot Account Detail #' #' ### Description - #' Retrieves detailed financial metrics for a specific spot account identified by its `accountId` from the KuCoin API asynchronously. This method calls `get_spot_account_detail_impl` and requires an account ID, obtainable via `get_spot_account_list()`. + #' Retrieves detailed financial metrics for a specific spot account asynchronously via a GET request to `/api/v1/accounts/{accountId}`. + #' Calls `get_spot_account_detail_impl`. #' #' ### Workflow Overview - #' 1. **URL Construction**: Embeds `accountId` into `/api/v1/accounts/{accountId}` and combines with the base URL. - #' 2. **Header Preparation**: Constructs authentication headers using `build_headers()`. - #' 3. **API Request**: Sends a GET request with a 3-second timeout via `httr::GET()`. - #' 4. **Response Processing**: Converts the `"data"` field into a `data.table`, handling empty responses. + #' 1. **Request**: Constructs authenticated GET request with `accountId`. + #' 2. **Response**: Returns a `data.table` with account metrics. #' #' ### API Endpoint #' `GET https://api.kucoin.com/api/v1/accounts/{accountId}` #' #' ### Usage - #' Utilised by users to obtain detailed metrics for a specific spot account, such as balance and availability, after identifying the account ID. + #' Utilised to inspect a specific spot account’s financial status using an ID from `get_spot_account_list`. #' #' ### Official Documentation #' [KuCoin Get Account Detail Spot](https://www.kucoin.com/docs-new/rest/account-info/account-funding/get-account-detail-spot) #' - #' @param accountId Character string; unique account ID (e.g., from `get_spot_account_list()`). + #' ### Automated Trading Usage + #' - **Balance Monitoring**: Check `available` vs. `holds` to manage trading liquidity, triggering transfers if needed. + #' - **Account Drill-Down**: Use after `get_spot_account_list` to focus on high-value accounts, logging discrepancies. + #' - **Risk Assessment**: Monitor `holds` to detect pending orders or freezes, adjusting risk parameters. #' - #' @return Promise resolving to a `data.table` containing: - #' - `currency` (character): Currency of the account. + #' @param accountId Character string; unique account ID (e.g., from `get_spot_account_list`). Required. + #' @return Promise resolving to a `data.table` with: + #' - `currency` (character): Currency code. #' - `balance` (numeric): Total funds. #' - `available` (numeric): Available funds. #' - `holds` (numeric): Funds on hold. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": {"currency": "USDT", "balance": "1000", "available": "900", "holds": "100"}} + #' ``` get_spot_account_detail = function(accountId) { return(get_spot_account_detail_impl(self$keys, self$base_url, accountId)) }, - #' Retrieve Cross Margin Account Information + #' Get Cross Margin Account #' #' ### Description - #' Retrieves detailed information about the cross margin account asynchronously, including overall metrics and individual accounts. Cross margin allows collateral use across multiple trading pairs. This method calls `get_cross_margin_account_impl`. + #' Retrieves cross margin account details asynchronously via a GET request to `/api/v3/margin/accounts`. + #' Calls `get_cross_margin_account_impl`. #' #' ### Workflow Overview - #' 1. **URL Construction**: Combines the base URL with `/api/v3/margin/accounts` and a query string from `build_query()`. - #' 2. **Header Preparation**: Constructs authentication headers using `build_headers()`. - #' 3. **API Request**: Sends a GET request with a 3-second timeout via `httr::GET()`. - #' 4. **Response Processing**: Splits the `"data"` field into `summary` and `accounts` `data.table` objects. + #' 1. **Query**: Applies optional filters from `query`. + #' 2. **Request**: Constructs authenticated GET request. + #' 3. **Response**: Returns a list with `summary` and `accounts` `data.table`s. #' #' ### API Endpoint #' `GET https://api.kucoin.com/api/v3/margin/accounts` #' #' ### Usage - #' Utilised by users to monitor cross margin account status, including total assets, liabilities, and per-currency details. + #' Utilised to monitor cross margin account status, including total assets and per-currency details. #' #' ### Official Documentation #' [KuCoin Get Account Cross Margin](https://www.kucoin.com/docs-new/rest/account-info/account-funding/get-account-cross-margin) #' - #' @param query Named list of query parameters: - #' - `quoteCurrency` (character, optional): Quote currency (e.g., `"USDT"`, `"KCS"`, `"BTC"`; default `"USDT"`). - #' - `queryType` (character, optional): Account type (`"MARGIN"`, `"MARGIN_V2"`, `"ALL"`; default `"MARGIN"`). + #' ### Automated Trading Usage + #' - **Risk Management**: Track `debtRatio` in `summary` to adjust leverage, halting trades if risk exceeds thresholds. + #' - **Fund Allocation**: Monitor `available` in `accounts` to optimize margin usage across currencies. + #' - **Currency Filter**: Use `query$quoteCurrency` to focus on primary trading assets (e.g., "USDT"), syncing with market conditions. #' - #' @return Promise resolving to a named list containing: - #' - `summary`: `data.table` with: + #' @param query Named list; optional filters: + #' - `quoteCurrency` (character): Quote currency (e.g., "USDT", default "USDT"). + #' - `queryType` (character): Account type ("MARGIN", "MARGIN_V2", "ALL", default "MARGIN"). + #' @return Promise resolving to a list with: + #' - `summary`: `data.table`: #' - `totalAssetOfQuoteCurrency` (character): Total assets. - #' - `totalLiabilityOfQuoteCurrency` (character): Total liabilities. #' - `debtRatio` (character): Debt ratio. - #' - `status` (character): Position status (e.g., `"EFFECTIVE"`). - #' - `accounts`: `data.table` with: + #' - `accounts`: `data.table`: #' - `currency` (character): Currency code. #' - `total` (character): Total funds. #' - `available` (character): Available funds. - #' - `hold` (character): Funds on hold. - #' - `liability` (character): Liabilities. - #' - `maxBorrowSize` (character): Maximum borrowable amount. - #' - `borrowEnabled` (logical): Borrowing enabled. - #' - `transferInEnabled` (logical): Transfer-in enabled. + #' - Full schema in implementation docs. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": {"totalAssetOfQuoteCurrency": "1000", "accounts": [{"currency": "USDT", "total": "500"}]}} + #' ``` get_cross_margin_account = function(query = list()) { return(get_cross_margin_account_impl(self$keys, self$base_url, query)) }, - #' Retrieve Isolated Margin Account Information + #' Get Isolated Margin Account #' #' ### Description - #' Retrieves isolated margin account details for specific trading pairs from the KuCoin API asynchronously, segregating collateral by pair. This method calls `get_isolated_margin_account_impl`. + #' Retrieves isolated margin account details asynchronously via a GET request to `/api/v3/isolated/accounts`. + #' Calls `get_isolated_margin_account_impl`. #' #' ### Workflow Overview - #' 1. **URL Construction**: Combines the base URL with `/api/v3/isolated/accounts` and a query string from `build_query()`. - #' 2. **Header Preparation**: Constructs authentication headers using `build_headers()`. - #' 3. **API Request**: Sends a GET request with a 3-second timeout via `httr::GET()`. - #' 4. **Response Processing**: Converts the `"data"` field into `summary` and flattened `assets` `data.table` objects, adding a `datetime` column. + #' 1. **Query**: Applies optional filters from `query`. + #' 2. **Request**: Constructs authenticated GET request. + #' 3. **Response**: Returns a list with `summary` and `assets` `data.table`s. #' #' ### API Endpoint #' `GET https://api.kucoin.com/api/v3/isolated/accounts` #' #' ### Usage - #' Utilised by users to monitor isolated margin accounts, providing detailed asset and liability data per trading pair. + #' Utilised to monitor isolated margin accounts per trading pair, detailing assets and liabilities. #' #' ### Official Documentation #' [KuCoin Get Account Isolated Margin](https://www.kucoin.com/docs-new/rest/account-info/account-funding/get-account-isolated-margin) #' - #' @param query Named list of query parameters: - #' - `symbol` (character, optional): Trading pair (e.g., `"BTC-USDT"`). - #' - `quoteCurrency` (character, optional): Quote currency (e.g., `"USDT"`, `"KCS"`, `"BTC"`; default `"USDT"`). - #' - `queryType` (character, optional): Type (`"ISOLATED"`, `"ISOLATED_V2"`, `"ALL"`; default `"ISOLATED"`). - #' - #' @return Promise resolving to a named list containing: - #' - `summary`: `data.table` with: + #' ### Automated Trading Usage + #' - **Pair-Specific Risk**: Monitor `debtRatio` per `symbol` in `assets` to manage isolated leverage, adjusting positions dynamically. + #' - **Liquidity Check**: Use `base_available` and `quote_available` to ensure sufficient margin, triggering fund transfers if low. + #' - **Time-Based Sync**: Leverage `datetime` in `summary` to validate data freshness, polling hourly for critical pairs. + #' + #' @param query Named list; optional filters: + #' - `symbol` (character): Trading pair (e.g., "BTC-USDT"). + #' - `quoteCurrency` (character): Quote currency (e.g., "USDT", default "USDT"). + #' - `queryType` (character): Type ("ISOLATED", "ISOLATED_V2", "ALL", default "ISOLATED"). + #' @return Promise resolving to a list with: + #' - `summary`: `data.table`: #' - `totalAssetOfQuoteCurrency` (character): Total assets. - #' - `totalLiabilityOfQuoteCurrency` (character): Total liabilities. - #' - `timestamp` (integer): Timestamp in milliseconds. - #' - `datetime` (POSIXct): Converted datetime. - #' - `assets`: `data.table` with: + #' - `datetime` (POSIXct): Snapshot time. + #' - `assets`: `data.table`: #' - `symbol` (character): Trading pair. - #' - `status` (character): Position status. - #' - `debtRatio` (character): Debt ratio. - #' - `base_currency` (character): Base currency code. - #' - `base_borrowEnabled` (logical): Base borrowing enabled. - #' - `base_transferInEnabled` (logical): Base transfer-in enabled. - #' - `base_liability` (character): Base liability. #' - `base_total` (character): Base total funds. - #' - `base_available` (character): Base available funds. - #' - `base_hold` (character): Base funds on hold. - #' - `base_maxBorrowSize` (character): Base max borrowable. - #' - `quote_currency` (character): Quote currency code. - #' - `quote_borrowEnabled` (logical): Quote borrowing enabled. - #' - `quote_transferInEnabled` (logical): Quote transfer-in enabled. #' - `quote_liability` (character): Quote liability. - #' - `quote_total` (character): Quote total funds. - #' - `quote_available` (character): Quote available funds. - #' - `quote_hold` (character): Quote funds on hold. - #' - `quote_maxBorrowSize` (character): Quote max borrowable. + #' - Full schema in implementation docs. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": {"totalAssetOfQuoteCurrency": "1000", "assets": [{"symbol": "BTC-USDT", "base_total": "0.1"}]}} + #' ``` get_isolated_margin_account = function(query = list()) { return(get_isolated_margin_account_impl(self$keys, self$base_url, query)) }, - #' Retrieve Spot Ledger Records + #' Get Spot Ledger #' #' ### Description - #' Retrieves detailed ledger records for spot and margin accounts from the KuCoin API asynchronously with pagination, aggregating transaction histories into a `data.table`. This method calls `get_spot_ledger_impl`. + #' Retrieves paginated ledger records for spot and margin accounts asynchronously via a GET request to `/api/v1/accounts/ledgers`. + #' Calls `get_spot_ledger_impl`. #' #' ### Workflow Overview - #' 1. **URL Construction**: Combines the base URL with `/api/v1/accounts/ledgers`, merging query parameters with pagination settings. - #' 2. **Header Preparation**: Constructs authentication headers using `build_headers()` within an inner async function. - #' 3. **API Request**: Utilises `auto_paginate` to fetch all pages asynchronously via an inner `fetch_page` function. - #' 4. **Response Processing**: Aggregates `"items"` from each page into a `data.table`, adding a `createdAtDatetime` column. + #' 1. **Query**: Applies filters and pagination from `query`, `page_size`, and `max_pages`. + #' 2. **Request**: Constructs authenticated GET request with pagination. + #' 3. **Response**: Returns a `data.table` of transaction history. #' #' ### API Endpoint #' `GET https://api.kucoin.com/api/v1/accounts/ledgers` #' #' ### Usage - #' Utilised by users to retrieve transaction histories for spot and margin accounts, filterable by currency, direction, and time range. + #' Utilised to track transaction histories for spot and margin accounts, filterable by various criteria. #' #' ### Official Documentation #' [KuCoin Get Account Ledgers Spot Margin](https://www.kucoin.com/docs-new/rest/account-info/account-funding/get-account-ledgers-spot-margin) #' - #' @param query Named list of query parameters (excluding pagination): - #' - `currency` (character, optional): Filter by currency (up to 10). - #' - `direction` (character, optional): `"in"` or `"out"`. - #' - `bizType` (character, optional): Business type (e.g., `"DEPOSIT"`, `"TRANSFER"`). - #' - `startAt` (integer, optional): Start time in milliseconds. - #' - `endAt` (integer, optional): End time in milliseconds. - #' @param page_size Integer; number of results per page (10–500, default 50). - #' @param max_pages Numeric; maximum number of pages to fetch (default `Inf` for all pages). - #' - #' @return Promise resolving to a `data.table` containing: - #' - `id` (character): Ledger record ID. - #' - `currency` (character): Currency. + #' ### Automated Trading Usage + #' - **Transaction Audit**: Filter by `bizType = "TRANSFER"` to reconcile internal movements, logging `amount` and `createdAtDatetime`. + #' - **Fee Analysis**: Sum `fee` over time ranges to optimize trading costs, adjusting strategies accordingly. + #' - **Event Monitoring**: Use `direction` and `context` to detect deposits/withdrawals, triggering fund allocation or alerts. + #' + #' @param query Named list; optional filters: + #' - `currency` (character): Currency code (up to 10). + #' - `direction` (character): "in" or "out". + #' - `bizType` (character): Business type (e.g., "DEPOSIT"). + #' - `startAt` (integer): Start time (ms). + #' - `endAt` (integer): End time (ms). + #' @param page_size Integer; results per page (10-500, default 50). + #' @param max_pages Numeric; max pages to fetch (default `Inf`). + #' @return Promise resolving to a `data.table` with: + #' - `id` (character): Ledger ID. + #' - `currency` (character): Currency code. #' - `amount` (character): Transaction amount. - #' - `fee` (character): Transaction fee. - #' - `balance` (character): Post-transaction balance. - #' - `accountType` (character): Account type. - #' - `bizType` (character): Business type. - #' - `direction` (character): Transaction direction. - #' - `createdAt` (integer): Timestamp in milliseconds. - #' - `createdAtDatetime` (POSIXct): Converted datetime. - #' - `context` (character): Transaction context. - #' - `currentPage` (integer): Current page number. - #' - `pageSize` (integer): Page size. - #' - `totalNum` (integer): Total records. - #' - `totalPage` (integer): Total pages. + #' - `createdAtDatetime` (POSIXct): Transaction time. + #' - Full schema in implementation docs. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": {"items": [{"id": "xyz", "currency": "BTC", "amount": "0.1", "createdAt": 1733049198863}]}} + #' ``` get_spot_ledger = function(query = list(), page_size = 50, max_pages = Inf) { return(get_spot_ledger_impl( keys = self$keys, diff --git a/R/KucoinDeposit.R b/R/KucoinDeposit.R index e33a9d8c..1d6f6ae2 100644 --- a/R/KucoinDeposit.R +++ b/R/KucoinDeposit.R @@ -9,66 +9,62 @@ # ./utils[get_api_keys, get_base_url] # ) -#' KucoinDeposit Class for KuCoin Deposit Endpoints +#' KucoinDeposit Class for KuCoin Deposit Management #' -#' The `KucoinDeposit` class provides an asynchronous interface for managing deposits on KuCoin. -#' It leverages the `coro` package for non-blocking HTTP requests, returning promises that typically resolve to `data.table` -#' objects. This class supports creating new deposit addresses, retrieving existing deposit addresses, and fetching deposit history. +#' The `KucoinDeposit` class provides an asynchronous interface for managing deposit operations on KuCoin. +#' It leverages the `coro` package for non-blocking HTTP requests, returning promises that resolve to `data.table` objects. +#' This class supports creating new deposit addresses, retrieving existing deposit addresses, and fetching deposit history, +#' all requiring authentication via API keys. #' -#' ### Workflow Overview -#' Not applicable (class definition overview). -#' -#' ### API Endpoint -#' Not applicable (class-level documentation; see individual methods). +#' ### Purpose and Scope +#' This class is designed to handle deposit-related tasks in the KuCoin ecosystem, including: +#' - **Address Creation**: Generating new deposit addresses for various currencies and chains. +#' - **Address Retrieval**: Listing all deposit addresses for a currency. +#' - **History Tracking**: Querying deposit records with filtering and pagination. #' #' ### Usage -#' Utilised by users to manage KuCoin deposits programmatically. The class is initialised with API credentials, -#' automatically loaded via `get_api_keys()` if not provided, and a base URL from `get_base_url()`. For detailed endpoint -#' information and response schemas, refer to the official [KuCoin API Documentation](https://www.kucoin.com/docs-new). +#' Utilised by traders and developers to programmatically manage deposits on KuCoin. The class is initialized with API credentials, +#' automatically sourced from `get_api_keys()` if not provided, and a base URL from `get_base_url()`. All methods require authentication. +#' For detailed endpoint information, parameters, and response schemas, refer to the official [KuCoin API Documentation](https://www.kucoin.com/docs-new). #' #' ### Official Documentation -#' [KuCoin API Documentation](https://www.kucoin.com/docs-new) +#' [KuCoin API Documentation - Deposit](https://www.kucoin.com/docs-new/rest/account-info/deposit/introduction) #' #' @section Methods: -#' - **initialize(keys, base_url):** Initialises the object with API credentials and the base URL. -#' - **add_deposit_address(currency, chain, to, amount):** Creates a new deposit address for a specified currency. -#' - **get_deposit_addresses(currency, amount, chain):** Retrieves all deposit addresses for a specified currency. -#' - **get_deposit_history(currency, status, startAt, endAt, page_size, max_pages):** Retrieves the deposit history for a specified currency. -#' -#' @return Not applicable (class definition; see individual methods for return values). +#' - **initialize(keys, base_url):** Initialises the object with API credentials and base URL. +#' - **add_deposit_address(currency, chain, to, amount):** Creates a new deposit address for a currency. +#' - **get_deposit_addresses(currency, chain, amount):** Retrieves all deposit addresses for a currency. +#' - **get_deposit_history(currency, status, startAt, endAt, page_size, max_pages):** Fetches paginated deposit history. #' #' @examples #' \dontrun{ -#' # Comprehensive example demonstrating all methods +#' # Comprehensive example demonstrating key methods #' main_async <- coro::async(function() { #' # Initialise the class #' deposit <- KucoinDeposit$new() #' -#' # Add a new deposit address +#' # Add a new deposit address for USDT on TRON #' new_address <- await(deposit$add_deposit_address( #' currency = "USDT", #' chain = "trx", #' to = "trade" #' )) -#' print("New Deposit Address:") -#' print(new_address) +#' print("New Deposit Address:"); print(new_address) #' -#' # Get all deposit addresses for a currency +#' # Get all deposit addresses for USDT #' addresses <- await(deposit$get_deposit_addresses(currency = "USDT")) -#' print("Deposit Addresses:") -#' print(addresses) +#' print("USDT Deposit Addresses:"); print(addresses) #' -#' # Get deposit history +#' # Get deposit history for USDT over a specific period #' history <- await(deposit$get_deposit_history( #' currency = "USDT", #' status = "SUCCESS", -#' startAt = 1728663338000, -#' endAt = 1728692138000, -#' page_size = 50, +#' startAt = as.integer(Sys.time() - 24*3600) * 1000, +#' endAt = as.integer(Sys.time()) * 1000, +#' page_size = 10, #' max_pages = 2 #' )) -#' print("Deposit History:") -#' print(history) +#' print("USDT Deposit History:"); print(history) #' }) #' main_async() #' while (!later::loop_empty()) later::run_now() @@ -83,25 +79,30 @@ KucoinDeposit <- R6::R6Class( keys = NULL, #' @field base_url Character string representing the base URL for KuCoin API endpoints. base_url = NULL, - + #' Initialise a New KucoinDeposit Object #' #' ### Description - #' Initialises a `KucoinDeposit` object with API credentials and a base URL for managing KuCoin deposits asynchronously. - #' If not provided, credentials are sourced from `get_api_keys()` and the base URL from `get_base_url()`. + #' Initialises a `KucoinDeposit` object with API credentials and a base URL for managing deposit operations + #' asynchronously. All methods require authentication, so valid credentials are essential. #' #' ### Workflow Overview - #' 1. **Credential Assignment**: Sets `self$keys` to the provided or default API keys. - #' 2. **URL Assignment**: Sets `self$base_url` to the provided or default base URL. + #' 1. **Credential Assignment**: Sets `self$keys` to the provided or default API keys from `get_api_keys()`. + #' 2. **URL Assignment**: Sets `self$base_url` to the provided or default base URL from `get_base_url()`. #' #' ### API Endpoint #' Not applicable (initialisation method). #' #' ### Usage - #' Utilised to create an instance of the class with authentication details for deposit management. + #' Creates an instance for managing KuCoin deposits, requiring authenticated API access for all operations. #' #' ### Official Documentation - #' [KuCoin API Authentication](https://www.kucoin.com/docs-new/rest/introduction) + #' [KuCoin API Authentication](https://www.kucoin.com/docs-new/rest/introduction#authentication) + #' + #' ### Automated Trading Usage + #' - **Deposit Automation**: Use as the core object for deposit workflows in your bot, integrating with wallet management systems. + #' - **Secure Setup**: Provide explicit `keys` or use `get_api_keys()` from a secure vault for production-grade security. + #' - **Scalability**: Instantiate once and reuse across deposit cycles, pairing with withdrawal classes for full fund management. #' #' @param keys List containing API configuration parameters from `get_api_keys()`, including: #' - `api_key`: Character string; your KuCoin API key. @@ -116,43 +117,50 @@ KucoinDeposit <- R6::R6Class( self$keys <- keys self$base_url <- base_url }, - + #' Add Deposit Address #' #' ### Description - #' Creates a new deposit address for a specified currency on KuCoin asynchronously by sending a POST request to the `/api/v3/deposit-address/create` endpoint. - #' This method constructs a JSON request body, generates authentication headers, and processes the response into a `data.table`. - #' It calls `add_deposit_address_v3_impl`. + #' Creates a new deposit address for a specified currency asynchronously via a POST request to `/api/v3/deposit-address/create`. + #' Calls `add_deposit_address_v3_impl`. #' #' ### Workflow Overview - #' 1. **URL Construction**: Combines the base URL with `/api/v3/deposit-address/create`. - #' 2. **Request Body Preparation**: Builds a list with `currency`, `chain`, `to`, and optional `amount`, converted to JSON. - #' 3. **Header Preparation**: Generates authentication headers asynchronously using `build_headers()`. - #' 4. **API Request**: Sends a POST request with a 3-second timeout via `httr::POST()`. - #' 5. **Response Processing**: Validates the response and converts the `"data"` field into a `data.table`. + #' 1. **Validation**: Ensures `currency` is valid within the implementation. + #' 2. **Request Body**: Constructs JSON with `currency`, `chain`, `to`, and optional `amount`. + #' 3. **Authentication**: Generates headers with API keys. + #' 4. **API Call**: Sends POST request. + #' 5. **Response**: Returns address details as a `data.table`. #' #' ### API Endpoint #' `POST https://api.kucoin.com/api/v3/deposit-address/create` #' #' ### Usage - #' Utilised by users to create deposit addresses for various currencies, enabling deposits to the specified account type. + #' Utilised to generate new deposit addresses for funding KuCoin accounts, supporting various chains and account types. #' #' ### Official Documentation #' [KuCoin Add Deposit Address (V3)](https://www.kucoin.com/docs-new/rest/account-info/deposit/add-deposit-address-v3) #' - #' @param currency Character string; the currency for which to create the deposit address (e.g., "BTC", "ETH", "USDT"). - #' @param chain Character string (optional); the chain identifier (e.g., "eth", "bech32", "btc"). - #' @param to Character string (optional); the account type to deposit to ("main" or "trade"). - #' @param amount Character string (optional); the deposit amount, only used for Lightning Network invoices. + #' ### Automated Trading Usage + #' - **Fund Allocation**: Generate addresses for `to = "trade"` to direct funds to trading accounts, automating wallet-to-exchange transfers. + #' - **Chain Selection**: Specify `chain` (e.g., "trx" for USDT) to optimize fees, integrating with fee analysis from market data. + #' - **Address Rotation**: Create new addresses periodically for security, tracking via `chainId` and auditing with `get_deposit_addresses`. #' - #' @return Promise resolving to a `data.table` containing: - #' - `address` (character): The deposit address. - #' - `memo` (character): Address remark (may be empty). - #' - `chainId` (character): The chain identifier. - #' - `to` (character): The account type. - #' - `expirationDate` (integer): Expiration time (for Lightning Network). - #' - `currency` (character): The currency. - #' - `chainName` (character): The chain name. + #' @param currency Character string; currency code (e.g., "BTC", "USDT"). Required. + #' @param chain Character string; chain identifier (e.g., "trx", "erc20"). Optional. + #' @param to Character string; account type ("main" or "trade"). Optional, defaults to "main". + #' @param amount Character string; amount for Lightning Network invoices. Optional. + #' @return Promise resolving to a `data.table` with: + #' - `address` (character): Deposit address. + #' - `memo` (character): Address remark (if any). + #' - `chainId` (character): Chain identifier. + #' - `to` (character): Account type. + #' - `expirationDate` (integer): Expiration (Lightning Network). + #' - `currency` (character): Currency code. + #' - `chainName` (character): Chain name. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": {"address": "T...x", "memo": "", "chainId": "trx", "to": "trade", "currency": "USDT", "chainName": "TRON"}} + #' ``` add_deposit_address = function(currency, chain = NULL, to = NULL, amount = NULL) { return(add_deposit_address_v3_impl( keys = self$keys, @@ -163,97 +171,105 @@ KucoinDeposit <- R6::R6Class( amount = amount )) }, - + #' Get Deposit Addresses #' #' ### Description - #' Retrieves all deposit addresses for a specified currency on KuCoin asynchronously by sending a GET request to the `/api/v3/deposit-addresses` endpoint. - #' This method constructs the query string, generates authentication headers, and processes the response into a `data.table`. - #' It calls `get_deposit_addresses_v3_impl`. + #' Retrieves all deposit addresses for a specified currency asynchronously via a GET request to `/api/v3/deposit-addresses`. + #' Calls `get_deposit_addresses_v3_impl`. #' #' ### Workflow Overview - #' 1. **URL Construction**: Combines the base URL with `/api/v3/deposit-addresses` and appends query parameters. - #' 2. **Header Preparation**: Generates authentication headers asynchronously using `build_headers()`. - #' 3. **API Request**: Sends a GET request with a 3-second timeout via `httr::GET()`. - #' 4. **Response Processing**: Validates the response and converts the `"data"` array into a `data.table`. + #' 1. **Validation**: Ensures `currency` is valid within the implementation. + #' 2. **Query**: Builds query with `currency`, optional `chain`, and `amount`. + #' 3. **Authentication**: Generates headers with API keys. + #' 4. **API Call**: Sends GET request. + #' 5. **Response**: Returns a `data.table` of all addresses, empty if none exist. #' #' ### API Endpoint #' `GET https://api.kucoin.com/api/v3/deposit-addresses` #' #' ### Usage - #' Utilised by users to retrieve all existing deposit addresses for a given currency. + #' Utilised to list all existing deposit addresses for a currency, aiding in deposit management. #' #' ### Official Documentation #' [KuCoin Get Deposit Address (V3)](https://www.kucoin.com/docs-new/rest/account-info/deposit/get-deposit-address-v3) #' - #' @param currency Character string; the currency for which to retrieve deposit addresses (e.g., "BTC", "ETH", "USDT"). - #' @param amount Character string (optional); the deposit amount, only used for Lightning Network invoices. - #' @param chain Character string (optional); the chain identifier (e.g., "eth", "bech32", "btc"). + #' ### Automated Trading Usage + #' - **Address Inventory**: Fetch all addresses for a currency to manage multiple deposit points, selecting based on `to` or `chainName`. + #' - **Verification**: Confirm address availability before initiating deposits, retrying `add_deposit_address` if none exist. + #' - **Chain Preference**: Filter by `chain` to use low-fee networks, integrating with deposit history to track usage. #' - #' @return Promise resolving to a `data.table` containing: - #' - `address` (character): The deposit address. - #' - `memo` (character): Address remark (may be empty). - #' - `chainId` (character): The chain identifier. - #' - `to` (character): The account type ("main" or "trade"). - #' - `expirationDate` (integer): Expiration time (for Lightning Network). - #' - `currency` (character): The currency. - #' - `contractAddress` (character): The token contract address. - #' - `chainName` (character): The chain name. - get_deposit_addresses = function(currency, amount = NULL, chain = NULL) { + #' @param currency Character string; currency code (e.g., "BTC", "USDT"). Required. + #' @param chain Character string; chain identifier (e.g., "trx"). Optional. + #' @param amount Character string; amount for Lightning Network invoices. Optional. + #' @return Promise resolving to a `data.table` with: + #' - `address` (character): Deposit address. + #' - `memo` (character): Address remark (if any). + #' - `chainId` (character): Chain identifier. + #' - `to` (character): Account type. + #' - `expirationDate` (integer): Expiration (Lightning Network). + #' - `currency` (character): Currency code. + #' - `contractAddress` (character): Token contract address. + #' - `chainName` (character): Chain name. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": [{"address": "T...x", "memo": "", "chainId": "trx", "to": "trade", "currency": "USDT", "chainName": "TRON"}]} + #' ``` + get_deposit_addresses = function(currency, chain = NULL, amount = NULL) { return(get_deposit_addresses_v3_impl( keys = self$keys, base_url = self$base_url, currency = currency, - amount = amount, - chain = chain + chain = chain, + amount = amount )) }, - + #' Get Deposit History #' #' ### Description - #' Retrieves a paginated list of deposit history entries for a specified currency on KuCoin asynchronously by sending a GET request to the `/api/v1/deposits` endpoint. - #' This method handles pagination, constructs the query string, generates authentication headers, and processes the response into a `data.table` with a `createdAtDatetime` column. - #' It calls `get_deposit_history_impl`. + #' Retrieves paginated deposit history asynchronously via a GET request to `/api/v1/deposits`. + #' Calls `get_deposit_history_impl`. #' #' ### Workflow Overview - #' 1. **URL Construction**: Combines the base URL with `/api/v1/deposits` and appends query parameters for filters and pagination. - #' 2. **Pagination Initialisation**: Sets an initial query with `currentPage = 1` and the specified `page_size`. - #' 3. **Page Fetching**: Defines an async helper to fetch each page with authentication headers. - #' 4. **Automatic Pagination**: Uses `auto_paginate` to fetch all pages up to `max_pages`. - #' 5. **Response Processing**: Combines `"items"` from each page into a `data.table`, adding `createdAtDatetime`. + #' 1. **Validation**: Ensures parameters meet API constraints (e.g., `page_size` 10-500). + #' 2. **Query**: Constructs query with filters and pagination settings. + #' 3. **Authentication**: Generates headers with API keys. + #' 4. **API Call**: Fetches pages up to `max_pages`. + #' 5. **Response**: Aggregates history into a `data.table` with datetime conversion. #' #' ### API Endpoint #' `GET https://api.kucoin.com/api/v1/deposits` #' #' ### Usage - #' Utilised by users to fetch a comprehensive history of deposits for a KuCoin account, with optional filters for status and time range. + #' Utilised to track deposit transactions, with filtering by currency, status, and time range. #' #' ### Official Documentation #' [KuCoin Get Deposit History](https://www.kucoin.com/docs-new/rest/account-info/deposit/get-deposit-history) #' - #' @param currency Character string; the currency to filter deposits by (e.g., "BTC", "ETH", "USDT"). - #' @param status Character string (optional); the status to filter by ("PROCESSING", "SUCCESS", "FAILURE"). - #' @param startAt Integer (optional); start time in milliseconds to filter deposits (e.g., 1728663338000). - #' @param endAt Integer (optional); end time in milliseconds to filter deposits (e.g., 1728692138000). - #' @param page_size Integer; number of results per page (10–500, default 50). - #' @param max_pages Numeric; maximum number of pages to fetch (default `Inf` for all pages). + #' ### Automated Trading Usage + #' - **Fund Tracking**: Monitor `status = "SUCCESS"` deposits to confirm fund availability, triggering trading actions. + #' - **Reconciliation**: Use `createdAtDatetime` and `amount` to reconcile with external wallet records, polling daily with time filters. + #' - **Error Handling**: Filter `status = "FAILURE"` to investigate issues, alerting users or retrying deposits automatically. #' - #' @return Promise resolving to a `data.table` containing: - #' - `currency` (character): The currency of the deposit. - #' - `chain` (character): The chain identifier. + #' @param currency Character string; currency code (e.g., "BTC", "USDT"). Required. + #' @param status Character string; status filter ("PROCESSING", "SUCCESS", "FAILURE"). Optional. + #' @param startAt Integer; start time (ms). Optional. + #' @param endAt Integer; end time (ms). Optional. + #' @param page_size Integer; results per page (10-500, default 50). + #' @param max_pages Numeric; max pages to fetch (default `Inf`). + #' @return Promise resolving to a `data.table` with: + #' - `currency` (character): Currency code. + #' - `chain` (character): Chain identifier. #' - `status` (character): Deposit status. #' - `address` (character): Deposit address. - #' - `memo` (character): Address remark. - #' - `isInner` (logical): Whether the deposit is internal. #' - `amount` (character): Deposit amount. - #' - `fee` (character): Fee charged. - #' - `walletTxId` (character or NULL): Wallet transaction ID. - #' - `createdAt` (integer): Creation timestamp in milliseconds. - #' - `createdAtDatetime` (POSIXct): Converted creation datetime. - #' - `updatedAt` (integer): Last updated timestamp in milliseconds. - #' - `remark` (character): Additional remarks. - #' - `arrears` (logical): Whether the deposit is in arrears. + #' - `createdAtDatetime` (POSIXct): Creation time. + #' - Full schema in implementation docs. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": {"items": [{"currency": "USDT", "status": "SUCCESS", "amount": "100", "createdAt": 1733049198863}]}} + #' ``` get_deposit_history = function(currency, status = NULL, startAt = NULL, endAt = NULL, page_size = 50, max_pages = Inf) { return(get_deposit_history_impl( keys = self$keys, diff --git a/R/KucoinSubAccount.R b/R/KucoinSubAccount.R index 96a357ee..4e59e69d 100644 --- a/R/KucoinSubAccount.R +++ b/R/KucoinSubAccount.R @@ -1,72 +1,74 @@ # File: ./R/KucoinSubAccount.R # box::use( -# impl = ./impl_account_sub_account, -# ./utils[ get_api_keys, get_base_url ] +# ./impl_account_sub_account[ +# add_subaccount_impl, +# get_subaccount_list_summary_impl, +# get_subaccount_detail_balance_impl, +# get_subaccount_spot_v2_impl +# ], +# ./utils[get_api_keys, get_base_url] # ) -#' KucoinSubAccount Class for KuCoin Sub-Account Endpoints +#' KucoinSubAccount Class for KuCoin Sub-Account Management #' #' 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 typically resolve to `data.table` -#' objects. This class supports creating new sub-accounts, retrieving summary information for all sub-accounts, and fetching -#' detailed balance data for specific sub-accounts. +#' 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. #' -#' ### Workflow Overview -#' Not applicable (class definition overview). -#' -#' ### API Endpoint -#' Not applicable (class-level documentation; see individual methods). +#' ### 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 users to manage KuCoin sub-accounts programmatically. The class is initialised with API credentials, -#' automatically loaded via `get_api_keys()` if not provided, and a base URL from `get_base_url()`. For detailed endpoint -#' information and response schemas, refer to the official [KuCoin API Documentation](https://www.kucoin.com/docs-new). +#' 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](https://www.kucoin.com/docs-new). #' #' ### Official Documentation -#' [KuCoin API Documentation](https://www.kucoin.com/docs-new) +#' [KuCoin API Documentation - Sub-Account](https://www.kucoin.com/docs-new/rest/account-info/sub-account/introduction) #' #' @section Methods: -#' - **initialize(keys, base_url):** Initialises the object with API credentials and the base URL. -#' - **add_subaccount(password, subName, access, remarks):** Creates a new sub-account under the master account. +#' - **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):** Retrieves detailed balance information for a specific sub-account. -#' -#' @return Not applicable (class definition; see individual methods for return values). +#' - **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. #' #' @examples #' \dontrun{ -#' # Comprehensive example demonstrating all methods +#' # 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 = "TestPass123", -#' subName = "TestSub123", +#' password = "SecurePass123", +#' subName = "TradingSub1", #' access = "Spot", -#' remarks = "Test sub-account" +#' remarks = "Spot trading sub-account" #' )) -#' print("New Sub-Account:") -#' print(new_sub) +#' print("New Sub-Account:"); print(new_sub) #' -#' # Get summary of all sub-accounts -#' summary <- await(sub_acc$get_subaccount_list_summary(page_size = 50, max_pages = 2)) -#' print("Sub-Account Summary:") -#' print(summary) +#' # 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 details for the first sub-account (if any) +#' # 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) +#' print("Sub-Account Balance:"); print(balance) #' } -#' -#' # Get Spot sub-account list (V2) -#' spot_accounts <- await(sub_acc$get_subaccount_spot_v2(page_size = 50, max_pages = 2)) -#' print("Spot Sub-Accounts (V2):") +#' +#' # 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() @@ -85,21 +87,26 @@ KucoinSubAccount <- R6::R6Class( #' Initialise a New KucoinSubAccount Object #' #' ### Description - #' Initialises a `KucoinSubAccount` object with API credentials and a base URL for managing KuCoin sub-accounts asynchronously. - #' If not provided, credentials are sourced from `get_api_keys()` and the base URL from `get_base_url()`. + #' 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 - #' 1. **Credential Assignment**: Sets `self$keys` to the provided or default API keys. - #' 2. **URL Assignment**: Sets `self$base_url` to the provided or default base URL. + #' 1. **Credential Assignment**: Sets `self$keys` to the provided or default API keys from `get_api_keys()`. + #' 2. **URL Assignment**: Sets `self$base_url` to the provided or default base URL from `get_base_url()`. #' #' ### API Endpoint #' Not applicable (initialisation method). #' #' ### Usage - #' Utilised to create an instance of the class with authentication details for sub-account management. + #' Creates an instance for sub-account management, enabling creation, summary retrieval, and balance queries. #' #' ### Official Documentation - #' [KuCoin API Authentication](https://www.kucoin.com/docs-new/rest/introduction) + #' [KuCoin API Authentication](https://www.kucoin.com/docs-new/rest/introduction#authentication) + #' + #' ### 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 use `get_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. #' #' @param keys List containing API configuration parameters from `get_api_keys()`, including: #' - `api_key`: Character string; your KuCoin API key. @@ -118,36 +125,43 @@ KucoinSubAccount <- R6::R6Class( #' Add Sub-Account #' #' ### Description - #' Creates a new sub-account under the master account asynchronously by sending a POST request to the KuCoin API. - #' This method constructs a JSON request body, generates authentication headers, and processes the response into a `data.table`. - #' It calls `add_subaccount_impl`. + #' 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 - #' 1. **URL Construction**: Combines the base URL with `/api/v2/sub/user/created`. - #' 2. **Request Body Preparation**: Builds a list with `password`, `subName`, `access`, and optional `remarks`, converted to JSON. - #' 3. **Header Preparation**: Generates authentication headers asynchronously using `build_headers()`. - #' 4. **API Request**: Sends a POST request with a 3-second timeout via `httr::POST()`. - #' 5. **Response Processing**: Validates the response and converts the `"data"` field into a `data.table`. + #' 1. **Validation**: Ensures parameters meet API constraints within the implementation. + #' 2. **Request Body**: Constructs JSON with `password`, `subName`, `access`, and optional `remarks`. + #' 3. **Authentication**: Generates headers with API keys. + #' 4. **API Call**: Sends POST request. + #' 5. **Response**: Returns sub-account details as a `data.table`. #' #' ### API Endpoint #' `POST https://api.kucoin.com/api/v2/sub/user/created` #' #' ### Usage - #' Utilised by users to create sub-accounts for managing separate trading permissions within the KuCoin ecosystem. + #' Utilised to create sub-accounts with specific permissions for segregated trading or management purposes. #' #' ### Official Documentation #' [KuCoin Add Sub-Account](https://www.kucoin.com/docs-new/rest/account-info/sub-account/add-subaccount) #' - #' @param password Character string; sub-account password (7–24 characters, must contain letters and numbers). - #' @param subName Character string; sub-account name (7–32 characters, must include one letter and one number, no spaces). - #' @param access Character string; permission type (`"Spot"`, `"Futures"`, `"Margin"`). - #' @param remarks Character string (optional); remarks about the sub-account (1–24 characters if provided). - #' - #' @return Promise resolving to a `data.table` containing: - #' - `uid` (integer): Unique sub-account identifier. + #' ### Automated Trading Usage + #' - **Account Segregation**: Create sub-accounts with `access = "Spot"` for isolated trading strategies, assigning unique `subName`s for tracking. + #' - **Security**: Use strong, unique `password`s generated programmatically, storing securely with `remarks` for audit trails. + #' - **Post-Creation**: Follow with `get_subaccount_list_summary` to verify creation and retrieve `uid` for further operations. + #' + #' @param password Character string; sub-account password (7-24 characters, must include letters and numbers). Required. + #' @param subName Character string; sub-account name (7-32 characters, must include a letter and number, no spaces). Required. + #' @param access Character string; permission type ("Spot", "Futures", "Margin"). Required. + #' @param remarks Character string; optional remarks (1-24 characters if provided). + #' @return Promise resolving to a `data.table` with: + #' - `uid` (integer): Sub-account ID. #' - `subName` (character): Sub-account name. - #' - `remarks` (character): Provided remarks or notes. - #' - `access` (character): Permission type granted. + #' - `remarks` (character): Remarks (if provided). + #' - `access` (character): Permission type. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": {"uid": 169579801, "subName": "TestSub123", "remarks": "Test", "access": "Spot"}} + #' ``` add_subaccount = function(password, subName, access, remarks = NULL) { return(add_subaccount_impl( keys = self$keys, @@ -159,141 +173,128 @@ KucoinSubAccount <- R6::R6Class( )) }, - #' Get Sub-Account List Summary (Paginated) + #' Get Sub-Account List Summary #' #' ### Description - #' Retrieves a paginated summary of all sub-accounts associated with the master account asynchronously, aggregating results into a `data.table`. - #' This method converts `createdAt` timestamps to POSIXct and calls `get_subaccount_list_summary_impl`. + #' 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 - #' 1. **Pagination Initialisation**: Sets an initial query with `currentPage = 1` and specified `page_size`. - #' 2. **Page Fetching**: Defines an async helper to fetch each page with authentication headers. - #' 3. **Automatic Pagination**: Uses `auto_paginate` to fetch all pages up to `max_pages`. - #' 4. **Aggregation**: Combines results into a `data.table`, converting `createdAt` to `createdDatetime`. + #' 1. **Pagination**: Fetches pages with `page_size` up to `max_pages`. + #' 2. **Request**: Constructs authenticated GET request. + #' 3. **Response**: Aggregates results into a `data.table` with datetime conversion. #' #' ### API Endpoint #' `GET https://api.kucoin.com/api/v2/sub/user` #' #' ### Usage - #' Utilised by users to obtain a comprehensive overview of all sub-accounts, including creation details and permissions. + #' Utilised to obtain an overview of all sub-accounts, including creation details and permissions. #' #' ### Official Documentation #' [KuCoin Get Sub-Account List Summary Info](https://www.kucoin.com/docs-new/rest/account-info/sub-account/get-subaccount-list-summary-info) #' - #' @param page_size Integer; number of results per page (1–100, default 100). - #' @param max_pages Numeric; maximum number of pages to fetch (default `Inf` for all pages). + #' ### 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. #' - #' @return Promise resolving to a `data.table` containing: - #' - `currentPage` (integer): Current page number. - #' - `pageSize` (integer): Results per page. - #' - `totalNum` (integer): Total sub-accounts. - #' - `totalPage` (integer): Total pages. - #' - `userId` (character): Master account identifier. - #' - `uid` (integer): Sub-account identifier. + #' @param page_size Integer; results per page (1-100, default 100). + #' @param max_pages Numeric; max pages to fetch (default `Inf`). + #' @return Promise resolving to a `data.table` with: + #' - `uid` (integer): Sub-account ID. #' - `subName` (character): Sub-account name. - #' - `status` (integer): Sub-account status. - #' - `type` (integer): Sub-account type. - #' - `access` (character): Permission type (e.g., `"All"`, `"Spot"`). - #' - `createdAt` (integer): Creation timestamp in milliseconds. - #' - `createdDatetime` (POSIXct): Converted creation datetime. - #' - `remarks` (character): Sub-account remarks. + #' - `access` (character): Permission type. + #' - `createdDatetime` (POSIXct): Creation time. + #' - Full schema in implementation docs. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": {"items": [{"uid": 169579801, "subName": "TestSub123", "access": "Spot", "createdAt": 1668562696000}]}} + #' ``` get_subaccount_list_summary = function(page_size = 100, max_pages = Inf) { return(get_subaccount_list_summary_impl(self$keys, self$base_url, page_size, max_pages)) }, - #' Get Sub-Account Detail - Balance + #' Get Sub-Account Detail Balance #' #' ### Description - #' Retrieves detailed balance information for a specific sub-account identified by `subUserId` asynchronously. - #' This method aggregates balances across account types into a `data.table` and calls `get_subaccount_detail_balance_impl`. - #' Use `get_subaccount_list_summary()` to obtain `subUserId`. + #' 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 - #' 1. **URL Construction**: Combines the base URL with `/api/v1/sub-accounts/{subUserId}` and a query string for `includeBaseAmount`. - #' 2. **Header Preparation**: Generates authentication headers using `build_headers()`. - #' 3. **API Request**: Sends a GET request with a 3-second timeout via `httr::GET()`. - #' 4. **Response Processing**: Aggregates non-empty account type arrays (`mainAccounts`, etc.) into a `data.table`, adding `accountType`, `subUserId`, and `subName`. + #' 1. **Request**: Constructs authenticated GET request with `subUserId` and `includeBaseAmount`. + #' 2. **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 by users to monitor detailed balances across various account types for a specific sub-account. + #' Utilised to monitor financial details for a specific sub-account across various account types. #' #' ### Official Documentation #' [KuCoin Get Sub-Account Detail Balance](https://www.kucoin.com/docs-new/rest/account-info/sub-account/get-subaccount-detail-balance) #' - #' @param subUserId Character string; sub-account user ID (e.g., from `get_subaccount_list_summary()`). - #' @param includeBaseAmount Logical; whether to include currencies with zero balance (default `FALSE`). + #' ### Automated Trading Usage + #' - **Fund Monitoring**: Check `available` per `accountType` 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` from `get_subaccount_list_summary` to drill down into critical accounts, logging balances. #' - #' @return Promise resolving to a `data.table` containing: - #' - `currency` (character): Currency code. - #' - `balance` (character): Total balance. - #' - `available` (character): Available amount. - #' - `holds` (character): Locked amount. - #' - `accountType` (character): Source type (e.g., `"mainAccounts"`, `"tradeAccounts"`). - #' - `subUserId` (character): Sub-account user ID. + #' @param subUserId Character string; sub-account user ID (e.g., from `get_subaccount_list_summary`). Required. + #' @param includeBaseAmount Logical; include zero-balance currencies (default `FALSE`). + #' @return Promise resolving to a `data.table` with: + #' - `subUserId` (character): Sub-account ID. #' - `subName` (character): Sub-account name. - #' Additional fields like `baseCurrency`, `baseAmount` may be present. + #' - `accountType` (character): Account type (e.g., "mainAccounts"). + #' - `currency` (character): Currency code. + #' - `balance` (numeric): Total balance. + #' - Full schema in implementation docs. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": {"subUserId": "123", "subName": "TestSub", "mainAccounts": [{"currency": "USDT", "balance": "0.01"}]}} + #' ``` get_subaccount_detail_balance = function(subUserId, includeBaseAmount = FALSE) { return(get_subaccount_detail_balance_impl(self$keys, self$base_url, subUserId, includeBaseAmount)) }, - #' Get Spot Sub-Account List - Balance Details (V2) + #' Get Spot Sub-Account List (V2) #' #' ### Description - #' Retrieves paginated Spot sub-account balance information for all sub-accounts associated with the master account asynchronously, - #' aggregating results into a `data.table`. This method fetches data from the KuCoin API endpoint `/api/v2/sub-accounts`, processes - #' balance details across account types (`mainAccounts`, `tradeAccounts`, `marginAccounts`, `tradeHFAccounts`), and combines them - #' into a single table. It calls `get_subaccount_spot_v2_impl`. + #' 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 - #' 1. **Pagination Initialisation**: Sets an initial query with `currentPage = 1` and the specified `page_size`. - #' 2. **Page Fetching**: Defines an asynchronous helper to fetch each page, constructing the URL with query parameters and authentication headers. - #' 3. **Automatic Pagination**: Uses `auto_paginate` to fetch all pages up to `max_pages`, flattening items into a single list. - #' 4. **Balance Aggregation**: Processes each sub-account’s account type arrays, converting non-empty arrays into `data.table`s with an `accountType` column, - #' and aggregates them with `subUserId` and `subName`. - #' 5. **Type Casting**: Converts balance-related fields to numeric types for consistency. + #' 1. **Pagination**: Fetches pages with `page_size` up to `max_pages`. + #' 2. **Request**: Constructs authenticated GET request. + #' 3. **Response**: Aggregates balances across account types into a `data.table`. #' #' ### API Endpoint #' `GET https://api.kucoin.com/api/v2/sub-accounts` #' #' ### Usage - #' Utilised by users to obtain a comprehensive view of Spot sub-account balances across all sub-accounts under the master account. This method is ideal - #' for monitoring aggregated balance details without needing to query individual sub-accounts separately. + #' Utilised to obtain a comprehensive view of Spot sub-account balances across all sub-accounts. #' #' ### Official Documentation #' [KuCoin Get Sub-Account List - Spot Balance (V2)](https://www.kucoin.com/docs-new/rest/account-info/sub-account/get-subaccount-list-spot-balance-v2) #' - #' @param page_size Integer; number of sub-accounts per page (10–100, default 100). The KuCoin API enforces a minimum of 10 and a maximum of 100. - #' @param max_pages Numeric; maximum number of pages to fetch (default `Inf` for all pages). Use a finite value to limit the number of API requests. + #' ### Automated Trading Usage + #' - **Portfolio Overview**: Aggregate `balance` across `subUserId` and `accountType` 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. #' - #' @return Promise resolving to a `data.table` containing aggregated sub-account balance information, with columns: - #' - `subUserId` (character): Sub-account user ID. + #' @param page_size Integer; results per page (10-100, default 100). + #' @param max_pages Numeric; max pages to fetch (default `Inf`). + #' @return Promise resolving to a `data.table` with: + #' - `subUserId` (character): Sub-account ID. #' - `subName` (character): Sub-account name. - #' - `accountType` (character): Type of account (e.g., `"mainAccounts"`, `"tradeAccounts"`, `"marginAccounts"`, `"tradeHFAccounts"`). - #' - `currency` (character): Currency code (e.g., `"USDT"`). - #' - `balance` (numeric): Total balance in the currency. - #' - `available` (numeric): Amount available for trading or withdrawal. - #' - `holds` (numeric): Amount locked or held. - #' - `baseCurrency` (character): Base currency code (e.g., `"BTC"`). - #' - `baseCurrencyPrice` (numeric): Price of the base currency at the time of the snapshot. - #' - `baseAmount` (numeric): Equivalent amount in the base currency. - #' - `tag` (character): Tag associated with the account (e.g., `"DEFAULT"`). - #' - If no balances are present across all sub-accounts, an empty `data.table` is returned. - #' - #' @details - #' This method leverages the `/api/v2/sub-accounts` endpoint, which provides paginated data including balance details for each sub-account’s account types. - #' Sub-accounts with no balance entries (i.e., all account type arrays empty) are excluded from the result, focusing only on sub-accounts with active balances. - #' Pagination is handled automatically, respecting the API’s constraints on `pageSize` (10–100) and using `currentPage` to iterate through results. - #' Numeric fields are explicitly cast from character strings to ensure proper data types for downstream analysis. + #' - `accountType` (character): Account type (e.g., "tradeAccounts"). + #' - `currency` (character): Currency code. + #' - `balance` (numeric): Total balance. + #' - Full schema in implementation docs. + #' ### JSON Response Example + #' ```json + #' {"code": "200000", "data": {"items": [{"subUserId": "123", "subName": "TestSub", "tradeAccounts": [{"currency": "USDT", "balance": "0.01"}]}]}} + #' ``` get_subaccount_spot_v2 = function(page_size = 100, max_pages = Inf) { - return(impl$get_subaccount_spot_v2_impl( - keys = self$keys, - base_url = self$base_url, - page_size = page_size, - max_pages = max_pages - )) + return(get_subaccount_spot_v2_impl(self$keys, self$base_url, page_size, max_pages)) } ) )