KucoinMarginTrading: Margin Order and Debit Management
Source:R/KucoinMarginTrading.R
KucoinMarginTrading.RdKucoinMarginTrading: Margin Order and Debit Management
KucoinMarginTrading: Margin Order and Debit Management
Details
Provides intent-based methods for margin trading on KuCoin. Instead of
raw side = "buy" / side = "sell" parameters (which are ambiguous in a
margin context), this class exposes four clear actions:
open_long(): Buy an asset with borrowed funds (leveraged long).close_long(): Sell a previously-bought asset and repay the loan.open_short(): Borrow and sell an asset you don't own (short sell).close_short(): Buy back a previously-shorted asset and repay the loan.
Additionally provides methods for manual borrowing, repaying, interest queries, and leverage configuration. Inherits from KucoinBase.
How Margin Short Selling Works
open_short()borrows the base asset (e.g. BTC) and immediately sells it at market price. You now hold the proceeds (e.g. USDT) but owe the borrowed BTC plus interest.If the price drops,
close_short()buys back the asset at the lower price and automatically repays the loan. The difference is profit.If the price rises instead, you lose money — margin trading carries liquidation risk.
Cross vs Isolated Margin
Cross margin (default): All margin positions share the same collateral pool. A loss in one pair can be offset by gains in another, but a liquidation affects your entire margin account.
Isolated margin (
isIsolated = TRUE): Each trading pair has its own collateral. Losses are contained to that pair, but you need to allocate collateral per pair.
Usage
All methods require authentication (valid API key, secret, passphrase) with Margin permission enabled.
Endpoints Covered
| Method | Endpoint | HTTP |
| open_long / close_long / open_short / close_short | POST /api/v3/hf/margin/order | POST |
| borrow | POST /api/v3/margin/borrow | POST |
| repay | POST /api/v3/margin/repay | POST |
| get_borrow_history | GET /api/v3/margin/borrow | GET |
| get_repay_history | GET /api/v3/margin/repay | GET |
| get_interest_history | GET /api/v3/margin/interest | GET |
| get_borrow_rate | GET /api/v3/margin/borrowRate | GET |
| modify_leverage | POST /api/v3/position/update-user-leverage | POST |
Super class
kucoin::KucoinBase -> KucoinMarginTrading
Methods
Inherited methods
Method open_short()
Open a Short Position (Borrow and Sell)
Borrows the base asset and sells it immediately. This is how you bet
that an asset's price will go down. The exchange automatically
borrows the asset you are selling (you don't need to call borrow()
separately).
What happens under the hood:
KuCoin borrows the base asset (e.g. BTC) on your behalf.
That borrowed asset is immediately sold on the market.
You now owe the borrowed amount plus interest.
Use
close_short()later to buy it back and repay.
curl
curl --location --request POST 'https://api.kucoin.com/api/v3/hf/margin/order' \
--header 'Content-Type: application/json' \
--header 'KC-API-KEY: your-api-key' \
--header 'KC-API-SIGN: your-signature' \
--header 'KC-API-TIMESTAMP: 1729176273859' \
--header 'KC-API-PASSPHRASE: your-passphrase' \
--header 'KC-API-KEY-VERSION: 2' \
--data-raw '{"clientOid":"my-short-001","side":"sell","symbol":"BTC-USDT","type":"market","size":"0.001","autoBorrow":true,"autoRepay":false}'Usage
KucoinMarginTrading$open_short(
symbol,
size = NULL,
funds = NULL,
type = "market",
price = NULL,
isIsolated = FALSE,
clientOid = NULL,
stp = NULL,
remark = NULL,
timeInForce = NULL,
cancelAfter = NULL,
postOnly = NULL,
hidden = NULL,
iceberg = NULL,
visibleSize = NULL,
dry_run = FALSE
)Arguments
symbolCharacter; trading pair to short (e.g.,
"BTC-USDT"). You will borrow and sell the base currency (BTC in this example).sizeNumeric or NULL; quantity of the base asset to short. For market orders, specify either
size(base qty) orfunds(quote qty), not both.fundsNumeric or NULL; amount in quote currency to receive from the short sale. Only for market orders; mutually exclusive with
size.typeCharacter;
"limit"or"market"(default"market").priceNumeric or NULL; required for limit orders. The price at which to sell.
isIsolatedLogical;
TRUEfor isolated margin (risk limited to this pair),FALSE(default) for cross margin (shared collateral pool).clientOidCharacter or NULL; your own unique order ID (max 40 chars). Auto-generated if not provided (required by KuCoin for margin orders).
stpCharacter or NULL; self-trade prevention:
"CN","CO","CB","DC".remarkCharacter or NULL; order remark (max 20 ASCII chars).
timeInForceCharacter or NULL;
"GTC","GTT","IOC","FOK".cancelAfterNumeric or NULL; auto-cancel seconds (requires
timeInForce = "GTT").postOnlyLogical or NULL; if TRUE, order rejected if it would match immediately.
hiddenLogical or NULL; if TRUE, order hidden from order book.
icebergLogical or NULL; if TRUE, only
visibleSizeis shown.visibleSizeNumeric or NULL; visible quantity for iceberg orders.
dry_runLogical; if
TRUE, validates the order without actually placing it. Useful for testing your parameters. DefaultFALSE.
Returns
data.table (or promise<data.table> if constructed with async = TRUE) with columns:
order_id(character): KuCoin-assigned order identifier.client_oid(character): Client-provided order identifier.borrow_size(character): Amount borrowed.loan_apply_id(character): Loan application ID.
Examples
\dontrun{
margin <- KucoinMarginTrading$new()
# Market short: sell 0.001 BTC you don't own
order <- margin$open_short(symbol = "BTC-USDT", size = 0.001)
# Limit short: sell at a specific price
order <- margin$open_short(
symbol = "BTC-USDT", type = "limit",
price = 100000, size = 0.001
)
# Dry run (test without placing)
margin$open_short(symbol = "BTC-USDT", size = 0.001, dry_run = TRUE)
}
Method close_short()
Close a Short Position (Buy Back and Repay)
Buys back the base asset and automatically repays the loan. This
closes a short position opened with open_short().
What happens under the hood:
KuCoin buys the base asset (e.g. BTC) on the market.
The purchased asset is automatically used to repay your loan.
If the price dropped since you opened the short, you profit.
curl
curl --location --request POST 'https://api.kucoin.com/api/v3/hf/margin/order' \
--header 'Content-Type: application/json' \
--header 'KC-API-KEY: your-api-key' \
--header 'KC-API-SIGN: your-signature' \
--header 'KC-API-TIMESTAMP: 1729176273859' \
--header 'KC-API-PASSPHRASE: your-passphrase' \
--header 'KC-API-KEY-VERSION: 2' \
--data-raw '{"clientOid":"my-close-short-001","side":"buy","symbol":"BTC-USDT","type":"market","size":"0.001","autoBorrow":false,"autoRepay":true}'Usage
KucoinMarginTrading$close_short(
symbol,
size = NULL,
funds = NULL,
type = "market",
price = NULL,
isIsolated = FALSE,
clientOid = NULL,
stp = NULL,
remark = NULL,
timeInForce = NULL,
cancelAfter = NULL,
postOnly = NULL,
hidden = NULL,
iceberg = NULL,
visibleSize = NULL,
dry_run = FALSE
)Arguments
symbolCharacter; trading pair to close (must match the pair you shorted).
sizeNumeric or NULL; quantity of the base asset to buy back. Should match the size you shorted. For market orders, specify either
sizeorfunds, not both.fundsNumeric or NULL; amount in quote currency to spend buying back. Only for market orders; mutually exclusive with
size.typeCharacter;
"limit"or"market"(default"market").priceNumeric or NULL; required for limit orders.
isIsolatedLogical; must match the margin mode used in
open_short().clientOidCharacter or NULL; your own unique order ID.
stpCharacter or NULL; self-trade prevention.
remarkCharacter or NULL; order remark.
timeInForceCharacter or NULL;
"GTC","GTT","IOC","FOK".cancelAfterNumeric or NULL; auto-cancel seconds.
postOnlyLogical or NULL; passive order flag.
hiddenLogical or NULL; hidden order flag.
icebergLogical or NULL; iceberg order flag.
visibleSizeNumeric or NULL; visible quantity for iceberg.
dry_runLogical; if
TRUE, validates without placing. DefaultFALSE.
Method open_long()
Open a Leveraged Long Position (Borrow and Buy)
Borrows quote currency (e.g. USDT) and uses it to buy the base asset (e.g. BTC). This is how you take a leveraged bet that an asset's price will go up. The exchange automatically borrows the funds needed.
What happens under the hood:
KuCoin borrows the quote currency (e.g. USDT) on your behalf.
That borrowed currency is used to buy the base asset.
You now hold the asset but owe the borrowed amount plus interest.
Use
close_long()later to sell and repay.
curl
curl --location --request POST 'https://api.kucoin.com/api/v3/hf/margin/order' \
--header 'Content-Type: application/json' \
--header 'KC-API-KEY: your-api-key' \
--header 'KC-API-SIGN: your-signature' \
--header 'KC-API-TIMESTAMP: 1729176273859' \
--header 'KC-API-PASSPHRASE: your-passphrase' \
--header 'KC-API-KEY-VERSION: 2' \
--data-raw '{"clientOid":"my-long-001","side":"buy","symbol":"BTC-USDT","type":"market","size":"0.001","autoBorrow":true,"autoRepay":false}'Usage
KucoinMarginTrading$open_long(
symbol,
size = NULL,
funds = NULL,
type = "market",
price = NULL,
isIsolated = FALSE,
clientOid = NULL,
stp = NULL,
remark = NULL,
timeInForce = NULL,
cancelAfter = NULL,
postOnly = NULL,
hidden = NULL,
iceberg = NULL,
visibleSize = NULL,
dry_run = FALSE
)Arguments
symbolCharacter; trading pair to go long on (e.g.,
"BTC-USDT"). You will borrow quote currency (USDT) and buy the base (BTC).sizeNumeric or NULL; quantity of the base asset to buy.
fundsNumeric or NULL; amount in quote currency to spend. Only for market orders; mutually exclusive with
size.typeCharacter;
"limit"or"market"(default"market").priceNumeric or NULL; required for limit orders.
isIsolatedLogical;
TRUEfor isolated margin,FALSE(default) for cross.clientOidCharacter or NULL; your own unique order ID.
stpCharacter or NULL; self-trade prevention.
remarkCharacter or NULL; order remark.
timeInForceCharacter or NULL;
"GTC","GTT","IOC","FOK".cancelAfterNumeric or NULL; auto-cancel seconds.
postOnlyLogical or NULL; passive order flag.
hiddenLogical or NULL; hidden order flag.
icebergLogical or NULL; iceberg order flag.
visibleSizeNumeric or NULL; visible quantity for iceberg.
dry_runLogical; if
TRUE, validates without placing. DefaultFALSE.
Method close_long()
Close a Leveraged Long Position (Sell and Repay)
Sells the base asset and automatically repays the borrowed quote
currency. This closes a long position opened with open_long().
What happens under the hood:
KuCoin sells the base asset (e.g. BTC) on the market.
The proceeds are automatically used to repay your loan.
If the price rose since you opened the long, you profit.
curl
curl --location --request POST 'https://api.kucoin.com/api/v3/hf/margin/order' \
--header 'Content-Type: application/json' \
--header 'KC-API-KEY: your-api-key' \
--header 'KC-API-SIGN: your-signature' \
--header 'KC-API-TIMESTAMP: 1729176273859' \
--header 'KC-API-PASSPHRASE: your-passphrase' \
--header 'KC-API-KEY-VERSION: 2' \
--data-raw '{"clientOid":"my-close-long-001","side":"sell","symbol":"BTC-USDT","type":"market","size":"0.001","autoBorrow":false,"autoRepay":true}'Usage
KucoinMarginTrading$close_long(
symbol,
size = NULL,
funds = NULL,
type = "market",
price = NULL,
isIsolated = FALSE,
clientOid = NULL,
stp = NULL,
remark = NULL,
timeInForce = NULL,
cancelAfter = NULL,
postOnly = NULL,
hidden = NULL,
iceberg = NULL,
visibleSize = NULL,
dry_run = FALSE
)Arguments
symbolCharacter; trading pair to close (must match the pair you longed).
sizeNumeric or NULL; quantity of the base asset to sell.
fundsNumeric or NULL; amount in quote currency. Only for market orders; mutually exclusive with
size.typeCharacter;
"limit"or"market"(default"market").priceNumeric or NULL; required for limit orders.
isIsolatedLogical; must match the margin mode used in
open_long().clientOidCharacter or NULL; your own unique order ID.
stpCharacter or NULL; self-trade prevention.
remarkCharacter or NULL; order remark.
timeInForceCharacter or NULL;
"GTC","GTT","IOC","FOK".cancelAfterNumeric or NULL; auto-cancel seconds.
postOnlyLogical or NULL; passive order flag.
hiddenLogical or NULL; hidden order flag.
icebergLogical or NULL; iceberg order flag.
visibleSizeNumeric or NULL; visible quantity for iceberg.
dry_runLogical; if
TRUE, validates without placing. DefaultFALSE.
Method borrow()
Borrow Assets for Margin Trading
Manually borrows a specified amount of a currency for margin trading.
You typically don't need this if you use open_short() or
open_long() which auto-borrow for you. Use this for advanced
workflows where you want explicit control over the borrow/trade/repay
lifecycle.
Workflow
Validation: Checks required fields and types.
Request: Authenticated POST to borrow endpoint.
Parsing: Returns
data.tablewith loan details.
curl
curl --location --request POST 'https://api.kucoin.com/api/v3/margin/borrow' \
--header 'Content-Type: application/json' \
--header 'KC-API-KEY: your-api-key' \
--header 'KC-API-SIGN: your-signature' \
--header 'KC-API-TIMESTAMP: 1729176273859' \
--header 'KC-API-PASSPHRASE: your-passphrase' \
--header 'KC-API-KEY-VERSION: 2' \
--data-raw '{"currency":"USDT","size":"100","timeInForce":"IOC","isIsolated":false,"isHf":false}'Usage
KucoinMarginTrading$borrow(
currency,
size,
timeInForce = "IOC",
isIsolated = FALSE,
symbol = NULL,
isHf = FALSE
)Arguments
currencyCharacter; the currency to borrow (e.g.,
"USDT","BTC").sizeNumeric; the amount to borrow.
timeInForceCharacter; order time-in-force policy (default
"IOC"). Valid values:"IOC"(immediate-or-cancel),"FOK"(fill-or-kill).isIsolatedLogical;
TRUEfor isolated margin,FALSE(default) for cross.symbolCharacter or NULL; required when
isIsolated = TRUE. Trading pair (e.g.,"BTC-USDT").isHfLogical;
TRUEfor high-frequency trading mode,FALSE(default).
Method repay()
Repay Borrowed Assets
Manually repays a specified amount of a borrowed currency. You
typically don't need this if you use close_short() or
close_long() which auto-repay for you. Use this for advanced
workflows or to repay interest independently.
curl
curl --location --request POST 'https://api.kucoin.com/api/v3/margin/repay' \
--header 'Content-Type: application/json' \
--header 'KC-API-KEY: your-api-key' \
--header 'KC-API-SIGN: your-signature' \
--header 'KC-API-TIMESTAMP: 1729176273859' \
--header 'KC-API-PASSPHRASE: your-passphrase' \
--header 'KC-API-KEY-VERSION: 2' \
--data-raw '{"currency":"USDT","size":"100"}'Arguments
currencyCharacter; the currency to repay (e.g.,
"USDT","BTC").sizeNumeric; the amount to repay.
Method get_borrow_history()
Get Borrow History
Retrieves paginated borrow history records.
curl
curl --location --request GET \
'https://api.kucoin.com/api/v3/margin/borrow?currency=USDT¤tPage=1&pageSize=50' \
--header 'KC-API-KEY: your-api-key' \
--header 'KC-API-SIGN: your-signature' \
--header 'KC-API-TIMESTAMP: 1729176273859' \
--header 'KC-API-PASSPHRASE: your-passphrase' \
--header 'KC-API-KEY-VERSION: 2'Usage
KucoinMarginTrading$get_borrow_history(query = list())Arguments
queryNamed list; optional filter parameters. Supported keys:
currency(character): Filter by currency.isIsolated(logical): Filter by margin type.symbol(character): Filter by trading pair.orderNo(character): Filter by order number.startTime(integer): Start timestamp in milliseconds.endTime(integer): End timestamp in milliseconds.currentPage(integer): Page number.pageSize(integer): Items per page.
Method get_repay_history()
Get Repay History
Retrieves paginated repayment history records.
curl
curl --location --request GET \
'https://api.kucoin.com/api/v3/margin/repay?currency=USDT¤tPage=1&pageSize=50' \
--header 'KC-API-KEY: your-api-key' \
--header 'KC-API-SIGN: your-signature' \
--header 'KC-API-TIMESTAMP: 1729176273859' \
--header 'KC-API-PASSPHRASE: your-passphrase' \
--header 'KC-API-KEY-VERSION: 2'Usage
KucoinMarginTrading$get_repay_history(query = list())Method get_interest_history()
Get Interest History
Retrieves paginated interest accrual history for margin borrowing.
curl
curl --location --request GET \
'https://api.kucoin.com/api/v3/margin/interest?currency=USDT¤tPage=1&pageSize=50' \
--header 'KC-API-KEY: your-api-key' \
--header 'KC-API-SIGN: your-signature' \
--header 'KC-API-TIMESTAMP: 1729176273859' \
--header 'KC-API-PASSPHRASE: your-passphrase' \
--header 'KC-API-KEY-VERSION: 2'Usage
KucoinMarginTrading$get_interest_history(query = list())Arguments
queryNamed list; optional filter parameters. Supported keys:
currency(character): Filter by currency.isIsolated(logical): Cross vs isolated.symbol(character): Trading pair.startTime(integer): Start timestamp in milliseconds.endTime(integer): End timestamp in milliseconds.currentPage(integer): Page number.pageSize(integer): Items per page.
Method get_borrow_rate()
Get Borrow Interest Rate
Retrieves current borrow interest rates for one or more currencies.
curl
curl --location --request GET \
'https://api.kucoin.com/api/v3/margin/borrowRate?currency=BTC,USDT' \
--header 'KC-API-KEY: your-api-key' \
--header 'KC-API-SIGN: your-signature' \
--header 'KC-API-TIMESTAMP: 1729176273859' \
--header 'KC-API-PASSPHRASE: your-passphrase' \
--header 'KC-API-KEY-VERSION: 2'Usage
KucoinMarginTrading$get_borrow_rate(query = list())Arguments
queryNamed list; optional filter parameters. Supported keys:
currency(character): Comma-separated currency list (e.g.,"BTC,USDT").vipLevel(integer): VIP tier level.
Method modify_leverage()
Modify Leverage
Updates the leverage multiplier for the margin account. Higher leverage means you can borrow more relative to your collateral, but also increases liquidation risk.
curl
curl --location --request POST 'https://api.kucoin.com/api/v3/position/update-user-leverage' \
--header 'Content-Type: application/json' \
--header 'KC-API-KEY: your-api-key' \
--header 'KC-API-SIGN: your-signature' \
--header 'KC-API-TIMESTAMP: 1729176273859' \
--header 'KC-API-PASSPHRASE: your-passphrase' \
--header 'KC-API-KEY-VERSION: 2' \
--data-raw '{"leverage":"5"}'Examples
if (FALSE) { # \dontrun{
margin <- KucoinMarginTrading$new()
# --- Short selling workflow ---
# 1. Open short: borrow BTC and sell it immediately
order <- margin$open_short(symbol = "BTC-USDT", size = 0.001)
print(order)
# 2. Close short: buy back BTC and repay the loan
order <- margin$close_short(symbol = "BTC-USDT", size = 0.001)
print(order)
# --- Leveraged long workflow ---
# 1. Open long: borrow USDT and buy BTC with it
order <- margin$open_long(symbol = "BTC-USDT", size = 0.001)
print(order)
# 2. Close long: sell BTC and repay borrowed USDT
order <- margin$close_long(symbol = "BTC-USDT", size = 0.001)
print(order)
# --- Manual borrow/repay ---
loan <- margin$borrow(currency = "USDT", size = 100)
margin$repay(currency = "USDT", size = 100)
# --- Check rates before trading ---
rates <- margin$get_borrow_rate(query = list(currency = "BTC,USDT"))
print(rates)
} # }
## ------------------------------------------------
## Method `KucoinMarginTrading$open_short`
## ------------------------------------------------
if (FALSE) { # \dontrun{
margin <- KucoinMarginTrading$new()
# Market short: sell 0.001 BTC you don't own
order <- margin$open_short(symbol = "BTC-USDT", size = 0.001)
# Limit short: sell at a specific price
order <- margin$open_short(
symbol = "BTC-USDT", type = "limit",
price = 100000, size = 0.001
)
# Dry run (test without placing)
margin$open_short(symbol = "BTC-USDT", size = 0.001, dry_run = TRUE)
} # }
## ------------------------------------------------
## Method `KucoinMarginTrading$close_short`
## ------------------------------------------------
if (FALSE) { # \dontrun{
margin <- KucoinMarginTrading$new()
order <- margin$close_short(symbol = "BTC-USDT", size = 0.001)
print(order)
} # }
## ------------------------------------------------
## Method `KucoinMarginTrading$open_long`
## ------------------------------------------------
if (FALSE) { # \dontrun{
margin <- KucoinMarginTrading$new()
# Market long: buy 0.001 BTC with borrowed USDT
order <- margin$open_long(symbol = "BTC-USDT", size = 0.001)
# Limit long: buy at a specific price
order <- margin$open_long(
symbol = "BTC-USDT", type = "limit",
price = 50000, size = 0.001
)
} # }
## ------------------------------------------------
## Method `KucoinMarginTrading$close_long`
## ------------------------------------------------
if (FALSE) { # \dontrun{
margin <- KucoinMarginTrading$new()
order <- margin$close_long(symbol = "BTC-USDT", size = 0.001)
print(order)
} # }
## ------------------------------------------------
## Method `KucoinMarginTrading$borrow`
## ------------------------------------------------
if (FALSE) { # \dontrun{
margin <- KucoinMarginTrading$new()
# Cross margin borrow
loan <- margin$borrow(currency = "USDT", size = 100)
print(loan)
# Isolated margin borrow
loan <- margin$borrow(
currency = "BTC", size = 0.01,
isIsolated = TRUE, symbol = "BTC-USDT"
)
} # }
## ------------------------------------------------
## Method `KucoinMarginTrading$repay`
## ------------------------------------------------
if (FALSE) { # \dontrun{
margin <- KucoinMarginTrading$new()
result <- margin$repay(currency = "USDT", size = 100)
print(result)
} # }
## ------------------------------------------------
## Method `KucoinMarginTrading$get_borrow_history`
## ------------------------------------------------
if (FALSE) { # \dontrun{
margin <- KucoinMarginTrading$new()
history <- margin$get_borrow_history(query = list(currency = "USDT"))
print(history)
} # }
## ------------------------------------------------
## Method `KucoinMarginTrading$get_repay_history`
## ------------------------------------------------
if (FALSE) { # \dontrun{
margin <- KucoinMarginTrading$new()
history <- margin$get_repay_history(query = list(currency = "USDT"))
print(history)
} # }
## ------------------------------------------------
## Method `KucoinMarginTrading$get_interest_history`
## ------------------------------------------------
if (FALSE) { # \dontrun{
margin <- KucoinMarginTrading$new()
interest <- margin$get_interest_history(query = list(currency = "USDT"))
print(interest)
} # }
## ------------------------------------------------
## Method `KucoinMarginTrading$get_borrow_rate`
## ------------------------------------------------
if (FALSE) { # \dontrun{
margin <- KucoinMarginTrading$new()
rates <- margin$get_borrow_rate(query = list(currency = "BTC,USDT,ETH"))
print(rates)
} # }
## ------------------------------------------------
## Method `KucoinMarginTrading$modify_leverage`
## ------------------------------------------------
if (FALSE) { # \dontrun{
margin <- KucoinMarginTrading$new()
margin$modify_leverage(leverage = 5)
} # }