Documentation
General Info

Cede SDK API

The Cede SDK API is available via two integration options: the Typescript SDK or the on-premise HTTP SDK. Please select your preferred option below. You can seamlessly switch between the two at any time using the toggle button in the navigation bar.

Getting started

💡
To get a valid client ID, please contact us.

Cede SDK exposes its API via a JavaScript object. To use it, import it and create a new instance:

import CedeSDK from "@cedelabs-private/sdk";
 
const SDK_MODE = "REAL"; // or "MOCK", the default value is "MOCK"
const cedeSDK = new CedeSDK(SDK_MODE, { clientId: YOUR_CLIENT_ID });

Mode: "REAL" instance will use real exchange API, while "MOCK" instance will use mock API. The "MOCK" instance does not require a valid client ID and will let you test your integration without real funds and API keys.

Configuration:

  • clientId - string
    The client identifier. It is required for the "REAL" mode.
  • proxyUrl - string, optional
    This field specifies the proxy to be used for making private requests to exchanges, which is particularly useful when API keys are restricted to whitelisted IP addresses. If left unset, the SDK will bypass the proxy and send private requests directly.
  • cacheStorage - SdkCacheStorage, optional: By default, the Cede SDK utilizes InMemoryCacheStorage, which, as the name implies, stores cache data in memory. This means that when the server instance is shut down, all cached data is lost. To persist cache data beyond server restarts, you can implement a custom cache storage solution tailored to your needs or use RedisCacheStorage.

Supported exchanges

In order to fetch all supported exchanges and their specificities, use the following method:

method: getSupportedExchanges
response structure: Promise<ExchangeInfo[]>, see ExchangeInfo for details.

const supportedExchanges = await cedeSDK.api.getSupportedExchanges();

The ExchangeInfo type contains information regarding:

  • the exchange ID, name, and logo,
  • the exchange's status,
  • supported wallet types for fetching balances,
  • supported wallet types for internal transfers,
  • authentification mode and requirements,
  • the exchange's features and constraints (e.g. email confirmation, address whitelisting),

Authentication

To authenticate your requests, you must provide an auth parameter with every method you wish to invoke. You can use either a pair of API keys (apiKey and secretKey) or a pair of OAuth tokens (accessToken and refreshToken).

You'll also need to provide the exchangeInstanceId to methods that use private data, such as user balances. The SDK will use this identifier for caching. This identifier is unique for each user and exchange.

For example, if you're calling the getBalances method, you'll need to provide at least the exchangeInstanceId and auth parameters:

const auth = {
  exchangeId: CEDE_CEXS.BINANCE, // or any other exchange ID from `getSupportedExchanges` method
  apiKey: "your-api-key",
  secretKey: "your-secret-key",
};
const balances = await cedeSDK.api.getBalances({ exchangeInstanceId, auth });
💡
exchangeInstanceId is required in methods
💡

If you're in "MOCK" mode, you don't need to provide API keys or OAuth tokens in the auth parameter. However, the exchangeId is still needed.

Check the section below to learn how to get access and refresh tokens for OAuth authentication.

auth params for API key based authentication:

  • apiKey - string, optional
    A public API key. Required for exchanges using API keys for the SDK in "REAL" mode.
  • secretKey - string, optional
    A private API key. Required for exchanges using API keys for the SDK in "REAL" mode.
  • password - string, optional
    For exchanges requiring an additional password with API Keys. You get this information from getSupportedExchanges method.
  • uid - string, optional
    For exchanges requiring an additional UID with API Keys. You get this information from getSupportedExchanges method.
  • timeout - number, optional
    Timeout of the checks and registration (in milliseconds), the default value is 10_000.

auth params for OAuth based authentication:

  • accessToken - string, optional
    For OAuth authentication, an access token.
  • refreshToken - string, optional
    For OAuth authentication, a refresh token.
  • expiresAt - number, optional
    For OAuth authentication, a token expiration time.
  • deviceId - string, optional
    For exchanges requiring a Device ID with OAuth.
💡

In case of OAuth authentication, the SDK will automatically refresh the access token when it expires. However, if the refresh token expires, you will need to redirect the user to the OAuth flow again.

Revoke access

To revoke access for an OAuth2 connection, you can use the revokeOAuth method. This will invalidate the existing access and refresh tokens.

method: revokeOAuth
params:

  • exchangeInstanceId - string
    The exchange instance identifier.

response structure: Promise<void>

await cedeSDK.api.revokeOAuth({ exchangeInstanceId });

OAuth tokens

Get the list of exchanges supporting OAuth authentication with the getSupportedExchanges method and the auhenticationMethod field.

In case if you use OAuth authentication, first you'll need to provide your clientId and clientSecret to the SDK. We provide guides on how to get them for each exchange.

method: setupOAuthClientCredentials
params:

  • exchangeId - string
    The ID of the exchange you want to authenticate with.
  • clientId - string
    The client ID you got from the exchange.
  • clientSecret - string
    The client secret you got from the exchange. \

response structure: Promise<void>

cedeSdk.api.setupOAuthClientCredentials({
  exchangeId: "coinbase",
  clientId,
  clientSecret,
});

In order to get OAuth tokens, you need first to get the authorization code. To do that, you need to redirect the user to an URL provided by the Cede SDK:

method: getOAuthUrl
params:

  • exchangeId - string
    The exchange identifier.
  • redirectUri - string
    The URL to which the user will be redirected after the authorization.
  • permissions - ApiPermissions[]
    The permissions required for the OAuth token.
  • deviceId - string, optional
    For OKX, the device ID.

response structure: Promise<{ url: string; codeVerifier?: string }>, the codeVerifier is used by OKX, it will be needed for the getOAuthTokens method use.

const { url } = await cedeSDK.api.getOAuthUrl({
  exchangeId: "coinbase",
  redirectUri: "https://your-redirect-uri.com",
  permissions: ["read", "trade", "withdraw"],
});

After the user is redirected back to your app, copy the entire URL and pass it to the Cede SDK:

method: getOAuthTokens
params:

  • exchangeId - string
    The exchange identifier.
  • redirectUriWithCode - string
    The URL with the authorization code.
  • codeVerifier - string, optional
    The code verifier used for the OAuth token.
  • deviceId - string, optional
    The device ID used for the OAuth token.

response structure: Promise<{ accessToken: string; refreshToken: string; expiresAt: number; }

const { accessToken, refreshToken } = await cedeSDK.api.getOAuthTokens({
  exchangeId: "coinbase",
  redirectUriWithCode: "https://your-redirect-uri.com?code=123",
});

Now, you can register the exchange instance as specified above.

Errors

How to handle the SDK errors

Each Cede SDK method can throw errors, where each error is a class representing the scope of the issue. This allows you to handle errors in your code with specificity.

try {
  // ... your code
  await cedeSDK.api.createWithdrawal(...params);
} catch (error) {
  if (error instanceof OverWithdrawMaximumError) {
    // ... your logic to handle the case where the withdrawal amount is too high
  } else if (error instanceof WithdrawalError) {
    // ... handle the case where it's a withdrawal error
  } else if (error instanceof CedeSdkError) {
    // ... handle the case where it's a cede SDK generic error
  } else {
    // ... handle the case where it's a generic error
  }
}

There is an observable error hierarchy here. OverWithdrawMaximumError is a subclass of WithdrawalError, which in turn is a subclass of CedeSdkError. This allows you to catch the error at either a specific level or a more general level. In the given example, OverWithdrawMaximumError represents the specific error, while WithdrawalError represents the more general error for the withdrawal scope.

List of errors

You can see below the list of all the errors which can be thrown by the SDK. For your information, the first error of each section is the generic one, and the others are the inherited ones.

Cede SDK Errors

CodeClassDescription
10000DefaultErrorDefault SDK error
10001InvalidParamsErrorInvalid parameters provided to a SDK method
10002InvalidCacheErrorThrown when the cache can't be persisted
10003InvalidAddressErrorThe provided address is invalid
10004FetchFromCacheErrorAn error occured while fetching from the cache

Internal Errors

CodeClassDescription
11000InternalErrorDefault error for internal SDK errors
11001InvalidExchangeIdErrorAn invalid exchange id is provided
11002InvalidExchangeInstanceIdErrorAn invalid exchange instance id is provided

Authentication Errors

CodeClassDescription
12000AuthenticationErrorDefault error for authentication errors
12001InvalidCredentialsErrorInvalid credentials provided
12002AuthenticationFlowNotSupportedErrorAuthentication flow not supported
12003OAuthAccessRevokedErrorCan't perform the operation since the OAuth access are revoked

Withdrawal Errors

CodeClassDescription
13000WithdrawalErrorDefault error for withdrawal errors
13001ReadonlyExchangeNotProvidedErrorReadonly account not provided. It needs to be provided to perform some operations
13002TokenSymbolNotFoundErrorThe withdrawal can't be executed since the token symbol isn't found
13003WithdrawalNotFoundErrorThe withdrawal isn't found
13004UnderWithdrawMinimumErrorThe withdrawal amount is under the minimum amount allowed by the exchange
13005OverWithdrawMaximumErrorThe withdrawal amount is over the maximum amount allowed by the exchange
13006WhitelistCheckFailedErrorThe provided address isn't whitelisted for the withdrawal

Trade Errors

CodeClassDescription
14000TradeErrorDefault error for trade errors
14001MarketErrorDefault error for market errors
14002MarketNotFoundErrorThe given pair symbol was not found
14003OrderNotFoundErrorThe order isn't found
14004MarketNotLoadedErrorThe market isn't loaded
14005MarketTypeNotSupportedErrorThe market type isn't supported
14006InvalidOHLCVFormatErrorThe OHLCV format is invalid
14007CannotProvideOHLCVErrorCannot provide OHLCV data

Portfolio Errors

CodeClassDescription
15000PortfolioErrorDefault error for portfolio errors
15001InsufficientBalanceErrorThe user doesn't have enough balance to perform the operation

Deposit Errors

CodeClassDescription
16000DepositErrorDefault error for deposit errors
16001GetDepositAddressErrorCan't get the deposit address
16002CreateDepositAddressErrorCan't create the deposit address

Network Errors

CodeClassDescription
17000NetworkErrorDefault error for network errors
17001NetworkNotFoundErrorThe network isn't found

API Errors

CodeClassDescription
18000APIErrorDefault error for API errors
18001InvalidApiRequestErrorThe API request is invalid

Exchange Errors

CodeClassDescription
19000ExchangeErrorDefault error for exchange errors
19001ExchangeServerErrorThe exchange server is down
19002ExchangeUnderMaintenanceErrorThe exchange API is under maintenance
19003ExchangeRequestExpiredErrorThe exchange request is expired
19004ExchangeInvalidPermissionsErrorThe permissions are invalid to perform the operation
19005ExchangeTransferNotAllowedErrorTransfer is not allowed
19006ExchangeTransferErrorTransfer error
19007ExchangeDDosProtectionErrorDDoS protection error
19008ExchangeRateLimitExceededErrorRate limit exceeded
19010ExchangeUnknownAssetErrorUnknown asset
19011ExchangeOperationFailedErrorOperation failed
19012ExchangeAccountSuspendedErrorAccount suspended
19013ExchangeNotAllowedMethodErrorMethod isn't allowed to be called for an exchange
19014ExchangeNotAvailableErrorExchange is not available
19015ExchangeInvalidNonceErrorThe nonce is invalid
19016ExchangeUnavailableInCountryErrorExchange is unavailable in the country
19017ExchangeWalletTypeNotSupportedErrorWallet type not supported or not available for transfers

Identify an user

The Cede SDK collects client side errors. To identify an user and focus on the errors related to him, you can use the setUserId method. You have the responsability to provide a unique identifier for each user.

method: setUserId
params:

  • userId - string
    The user identifier.
💡
This method makes sense only if the SDK is implemented client side.
cedeSDK.setUserId("user-123");