add USDC perp client with tests

This commit is contained in:
tiagosiebler
2022-09-08 16:48:33 +01:00
parent 666720b27d
commit 5187350878
13 changed files with 583 additions and 37 deletions

View File

@@ -4,6 +4,7 @@ export * from './inverse-futures-client';
export * from './linear-client';
export * from './spot-client';
export * from './usdc-options-client';
export * from './usdc-perpetual-client';
export * from './websocket-client';
export * from './logger';
export * from './types';

View File

@@ -1,2 +1,3 @@
export * from './account-asset';
export * from './usdt-perp';
export * from './usdc-perp';

View File

@@ -0,0 +1,19 @@
export interface USDCKlineRequest {
symbol: string;
period: string;
startTime: number;
limit?: string;
}
export interface USDCOpenInterestRequest {
symbol: string;
period: string;
limit?: number;
}
export interface USDCLast500TradesRequest {
category: string;
symbol?: string;
baseCoin?: string;
limit?: string;
}

View File

@@ -25,6 +25,12 @@ export interface APIResponse<T> {
result: T;
}
export interface USDCAPIResponse<T> {
retCode: number;
retMsg: 'OK' | string;
result: T;
}
export interface APIResponseWithTime<T = {}> extends APIResponse<T> {
/** UTC timestamp */
time_now: numberInString;
@@ -37,15 +43,15 @@ export interface SymbolParam {
symbol: string;
}
export interface SymbolLimitParam {
export interface SymbolLimitParam<TLimit = number> {
symbol: string;
limit?: number;
limit?: TLimit;
}
export interface SymbolPeriodLimitParam {
export interface SymbolPeriodLimitParam<TLimit = number> {
symbol: string;
period: string;
limit?: number;
limit?: TLimit;
}
export interface SymbolFromLimitParam {

View File

@@ -7,7 +7,7 @@ import BaseRestClient from './util/BaseRestClient';
*/
export class USDCOptionsClient extends BaseRestClient {
getClientType() {
return REST_CLIENT_TYPE_ENUM.usdcOptions;
return REST_CLIENT_TYPE_ENUM.usdc;
}
async fetchServerTime(): Promise<number> {

View File

@@ -0,0 +1,287 @@
import {
APIResponseWithTime,
SymbolLimitParam,
SymbolPeriodLimitParam,
USDCAPIResponse,
USDCKlineRequest,
USDCLast500TradesRequest,
USDCOpenInterestRequest,
} from './types';
import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient';
/**
* REST API client for USDC Perpetual APIs
*/
export class USDCPerpetualClient extends BaseRestClient {
getClientType() {
return REST_CLIENT_TYPE_ENUM.usdc;
}
async fetchServerTime(): Promise<number> {
const res = await this.getServerTime();
return Number(res.time_now);
}
/**
*
* Market Data Endpoints
*
*/
getOrderBook(symbol: string): Promise<USDCAPIResponse<any>> {
return this.get('/perpetual/usdc/openapi/public/v1/order-book', { symbol });
}
/** Fetch trading rules (such as min/max qty). Query for all if blank. */
getContractInfo(params?: unknown): Promise<USDCAPIResponse<any>> {
return this.get('/perpetual/usdc/openapi/public/v1/symbols', params);
}
/** Get a symbol price/statistics ticker */
getSymbolTicker(symbol: string): Promise<USDCAPIResponse<any>> {
return this.get('/perpetual/usdc/openapi/public/v1/tick', { symbol });
}
getKline(params: USDCKlineRequest): Promise<USDCAPIResponse<any>> {
return this.get('/perpetual/usdc/openapi/public/v1/kline/list', params);
}
getMarkPrice(params: USDCKlineRequest): Promise<USDCAPIResponse<any>> {
return this.get(
'/perpetual/usdc/openapi/public/v1/mark-price-kline',
params
);
}
getIndexPrice(params: USDCKlineRequest): Promise<USDCAPIResponse<any>> {
return this.get(
'/perpetual/usdc/openapi/public/v1/index-price-kline',
params
);
}
getIndexPremium(params: USDCKlineRequest): Promise<USDCAPIResponse<any>> {
return this.get(
'/perpetual/usdc/openapi/public/v1/premium-index-kline',
params
);
}
getOpenInterest(
params: USDCOpenInterestRequest
): Promise<USDCAPIResponse<any>> {
return this.get('/perpetual/usdc/openapi/public/v1/open-interest', params);
}
getLargeOrders(
params: SymbolLimitParam<string>
): Promise<USDCAPIResponse<any>> {
return this.get('/perpetual/usdc/openapi/public/v1/big-deal', params);
}
getLongShortRatio(
params: SymbolPeriodLimitParam<string>
): Promise<USDCAPIResponse<any>> {
return this.get('/perpetual/usdc/openapi/public/v1/account-ratio', params);
}
getLast500Trades(
params: USDCLast500TradesRequest
): Promise<USDCAPIResponse<any>> {
return this.get(
'/option/usdc/openapi/public/v1/query-trade-latest',
params
);
}
/**
*
* Account Data Endpoints
*
*/
/** -> Order API */
/**
* Place an order using the USDC Derivatives Account.
* The request status can be queried in real-time.
* The response parameters must be queried through a query or a WebSocket response.
*/
submitOrder(params: unknown): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/perpetual/usdc/openapi/private/v1/place-order',
params
);
}
/** Active order parameters (such as quantity, price) and stop order parameters cannot be modified in one request at the same time. Please request modification separately. */
modifyOrder(params: unknown): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/perpetual/usdc/openapi/private/v1/replace-order',
params
);
}
/** Cancel order */
cancelOrder(params: unknown): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/perpetual/usdc/openapi/private/v1/cancel-order',
params
);
}
/** Cancel all active orders. The real-time response indicates whether the request is successful, depending on retCode. */
cancelActiveOrders(
symbol: string,
orderFilter: string
): Promise<USDCAPIResponse<any>> {
return this.postPrivate('/perpetual/usdc/openapi/private/v1/cancel-all', {
symbol,
orderFilter,
});
}
/** Query Unfilled/Partially Filled Orders */
getActiveOrders(params: unknown): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/option/usdc/openapi/private/v1/query-active-orders',
params
);
}
/** Query order history. The endpoint only supports up to 30 days of queried records */
getHistoricOrders(params: unknown): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/option/usdc/openapi/private/v1/query-order-history',
params
);
}
/** Query trade history. The endpoint only supports up to 30 days of queried records. An error will be returned if startTime is more than 30 days. */
getOrderExecutionHistory(params: unknown): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/option/usdc/openapi/private/v1/execution-list',
params
);
}
/** -> Account API */
/** The endpoint only supports up to 30 days of queried records. An error will be returned if startTime is more than 30 days. */
getTransactionLog(params: unknown): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/option/usdc/openapi/private/v1/query-transaction-log',
params
);
}
/** Wallet info for USDC account. */
getBalance(params?: unknown): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/option/usdc/openapi/private/v1/query-wallet-balance',
params
);
}
/** Asset Info */
getAssetInfo(baseCoin?: string): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/option/usdc/openapi/private/v1/query-asset-info',
{ baseCoin }
);
}
/**
* If USDC derivatives account balance is greater than X, you can open PORTFOLIO_MARGIN, and if it is less than Y, it will automatically close PORTFOLIO_MARGIN and change back to REGULAR_MARGIN. X and Y will be adjusted according to operational requirements.
* Rest API returns the result of checking prerequisites. You could get the real status of margin mode change by subscribing margin mode.
*/
setMarginMode(
newMarginMode: 'REGULAR_MARGIN' | 'PORTFOLIO_MARGIN'
): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/option/usdc/private/asset/account/setMarginMode',
{ setMarginMode: newMarginMode }
);
}
/** Query margin mode for USDC account. */
getMarginMode(): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/option/usdc/openapi/private/v1/query-margin-info'
);
}
/** -> Positions API */
/** Query my positions */
getPositions(params: unknown): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/option/usdc/openapi/private/v1/query-position',
params
);
}
/** Only for REGULAR_MARGIN */
setLeverage(symbol: string, leverage: string): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/perpetual/usdc/openapi/private/v1/position/leverage/save',
{ symbol, leverage }
);
}
/** Query Settlement History */
getSettlementHistory(params?: unknown): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/option/usdc/openapi/private/v1/session-settlement',
params
);
}
/** -> Risk Limit API */
/** Query risk limit */
getRiskLimit(symbol: string): Promise<USDCAPIResponse<any>> {
return this.getPrivate(
'/perpetual/usdc/openapi/public/v1/risk-limit/list',
{
symbol,
}
);
}
/** Set risk limit */
setRiskLimit(symbol: string, riskId: number): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/perpetual/usdc/openapi/private/v1/position/set-risk-limit',
{ symbol, riskId }
);
}
/** -> Funding API */
/** Funding settlement occurs every 8 hours at 00:00 UTC, 08:00 UTC and 16:00 UTC. The current interval's fund fee settlement is based on the previous interval's fund rate. For example, at 16:00, the settlement is based on the fund rate generated at 8:00. The fund rate generated at 16:00 will be used at 0:00 the next day. */
getLastFundingRate(symbol: string): Promise<USDCAPIResponse<any>> {
return this.get('/perpetual/usdc/openapi/public/v1/prev-funding-rate', {
symbol,
});
}
/** Get predicted funding rate and my predicted funding fee */
getPredictedFundingRate(symbol: string): Promise<USDCAPIResponse<any>> {
return this.postPrivate(
'/perpetual/usdc/openapi/private/v1/predicted-funding',
{ symbol }
);
}
/**
*
* API Data Endpoints
*
*/
getServerTime(): Promise<APIResponseWithTime> {
return this.get('/v2/public/time');
}
}

View File

@@ -124,7 +124,7 @@ export default abstract class BaseRestClient {
}
private isUSDCClient() {
return this.clientType === REST_CLIENT_TYPE_ENUM.usdcOptions;
return this.clientType === REST_CLIENT_TYPE_ENUM.usdc;
}
get(endpoint: string, params?: any) {

View File

@@ -61,23 +61,6 @@ export function getRestBaseUrl(
return exchangeBaseUrls.testnet;
}
export function isPublicEndpoint(endpoint: string): boolean {
const publicPrefixes = [
'v2/public',
'public/linear',
'spot/quote/v1',
'spot/v1/symbols',
'spot/v1/time',
];
for (const prefix of publicPrefixes) {
if (endpoint.startsWith(prefix)) {
return true;
}
}
return false;
}
export function isWsPong(response: any) {
if (response.pong || response.ping) {
return true;
@@ -101,7 +84,7 @@ export const REST_CLIENT_TYPE_ENUM = {
inverseFutures: 'inverseFutures',
linear: 'linear',
spot: 'spot',
usdcOptions: 'usdcOptions',
usdc: 'usdc',
} as const;
export type RestClientType =