okx-api
Version:
Complete Node.js SDK for OKX's REST APIs and WebSockets, with TypeScript & end-to-end tests
2,009 lines (1,962 loc) • 266 kB
Plain Text
This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix.
The content has been processed where content has been compressed (code blocks are separated by ⋮---- delimiter).
================================================================
File Summary
================================================================
Purpose:
--------
This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
File Format:
------------
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
a. A separator line (================)
b. The file path (File: path/to/file)
c. Another separator line
d. The full contents of the file
e. A blank line
Usage Guidelines:
-----------------
- This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
- When processing this file, use the file path to distinguish
between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
Notes:
------
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Content has been compressed - code blocks are separated by ⋮---- delimiter
- Files are sorted by Git change count (files with more changes are at the bottom)
================================================================
Directory Structure
================================================================
examples/
auth/
fasterHmacSign.ts
app.okx.com.ts
demo-trading.ts
my.okx.com.ts
README.md
rest-private-trade-market.ts
rest-private-trade.ts
rest-public.ts
ws-api-client.ts
ws-api-trade-raw.ts
ws-private-handle-auth-fail.ts
ws-private.ts
ws-public.ts
src/
constants/
funding.ts
types/
rest/
request/
account.ts
block-trading.ts
convert.ts
copy-trading.ts
funding.ts
grid-trading.ts
public.ts
recurring-buy.ts
shared.ts
signal-bot.ts
simple-earn.ts
spread-trading.ts
subaccount.ts
trade.ts
response/
private-account.ts
private-block-trading.ts
private-copy-trading.ts
private-flexible-loan.ts
private-funding.ts
private-recurring-buy.ts
private-signal-bot.ts
private-spread-trading.ts
private-subaccount.ts
private-trade.ts
public-data.ts
client.ts
shared.ts
websockets/
ws-api-request.ts
ws-api-response.ts
ws-api.ts
ws-events.ts
ws-general.ts
ws-request.ts
shared.ts
index.ts
rest-client.ts
websocket-api-client.ts
websocket-client-legacy.ts
websocket-client.ts
webpack/
webpack.config.js
.eslintrc.cjs
.gitignore
.jshintrc
.nvmrc
.prettierrc
jest.config.ts
LICENSE.md
package.json
postBuild.sh
README.md
tsconfig.cjs.json
tsconfig.esm.json
tsconfig.json
tsconfig.linting.json
================================================================
Files
================================================================
================
File: examples/README.md
================
# Examples
These samples can be executed using `ts-node`:
```
ts-node ./examples/rest-spot-public.ts
```
================
File: examples/rest-private-trade-market.ts
================
import { OrderRequest, RestClient } from '../src/index';
⋮----
// or
// import { RestClient, OrderRequest } from 'okx-api';
⋮----
// read from environmental variables
⋮----
// If running from CLI in unix, you can pass env vars as such:
// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-private-trade-market.ts
⋮----
// note the single quotes, preventing special characters such as $ from being incorrectly passed
⋮----
// apiKey: 'apiKeyHere',
⋮----
// apiSecret: 'apiSecretHere',
⋮----
// apiPass: 'apiPassHere',
⋮----
/** Get available balance for an asset */
async function getAssetBalance(
client: RestClient,
coin: string,
): Promise<number | null>
⋮----
/**
* This is a simple REST API demo script wrapped in a immediately invoked function expression. The logic below will immediately execute if you run this script.
*
* It is designed to:
* - check for any available USDT balance
* - immediately use half the balance to buy bitcoin (in spot)
* - check the available BTC balance
* - immediately sell all available BTC back to USDT
*/
================
File: examples/rest-public.ts
================
import { RestClient } from '../src/index';
⋮----
// or
// import { RestClient } from 'okx-api';
⋮----
/**
* This is a simple script wrapped in a immediately invoked function expression, designed to make public API calls without credentials
*/
================
File: src/constants/funding.ts
================
/**
* Asset bill type, auto-generated using table from funding asset bill details:
* https://www.okx.com/docs-v5/en/#rest-api-funding-asset-bills-details
*/
export enum ASSET_BILL_TYPE {
DEPOSIT = '1',
WITHDRAWAL = '2',
CANCELED_WITHDRAWAL = '13',
TRANSFER_TO_SUB_ACCOUNT = '20',
TRANSFER_FROM_SUB_ACCOUNT = '21',
CLAIM = '28',
SYSTEM_REVERSAL = '47',
RECEIVED_FROM_ACTIVITIES = '48',
GIVEN_AWAY_TO_ACTIVITIES = '49',
RECEIVED_FROM_APPOINTMENTS = '50',
DEDUCTED_FROM_APPOINTMENTS = '51',
RED_PACKET_SENT = '52',
RED_PACKET_SNATCHED = '53',
RED_PACKET_REFUNDED = '54',
CONVERSION = '61',
CLAIM_REBATE_CARD = '68',
DISTRIBUTE_REBATE_CARD = '69',
TOKEN_RECEIVED = '72',
TOKEN_GIVEN_AWAY = '73',
TOKEN_REFUNDED = '74',
SUBSCRIPTION_TO_SAVINGS = '75',
REDEMPTION_TO_SAVINGS = '76',
DISTRIBUTE = '77',
LOCK_UP = '78',
NODE_VOTING = '79',
STAKING_1 = '80',
VOTE_REDEMPTION = '81',
STAKING_REDEMPTION_1 = '82',
STAKING_YIELD = '83',
VIOLATION_FEE = '84',
POW_MINING_YIELD = '85',
CLOUD_MINING_PAY = '86',
CLOUD_MINING_YIELD = '87',
SUBSIDY = '88',
STAKING_2 = '89',
STAKING_SUBSCRIPTION = '90',
STAKING_REDEMPTION_2 = '91',
ADD_COLLATERAL = '92',
REDEEM_COLLATERAL = '93',
INVESTMENT = '94',
BORROWER_BORROWS = '95',
PRINCIPAL_TRANSFERRED_IN = '96',
BORROWER_TRANSFERRED_LOAN_OUT = '97',
BORROWER_TRANSFERRED_INTEREST_OUT = '98',
INVESTOR_TRANSFERRED_INTEREST_IN = '99',
PREPAYMENT_PENALTY_TRANSFERRED_IN = '102',
PREPAYMENT_PENALTY_TRANSFERRED_OUT = '103',
FEE_TRANSFERRED_IN = '104',
FEE_TRANSFERRED_OUT = '105',
OVERDUE_FEE_TRANSFERRED_IN = '106',
OVERDUE_FEE_TRANSFERRED_OUT = '107',
OVERDUE_INTEREST_TRANSFERRED_OUT = '108',
OVERDUE_INTEREST_TRANSFERRED_IN = '109',
COLLATERAL_FOR_CLOSED_POSITION_TRANSFERRED_IN = '110',
COLLATERAL_FOR_CLOSED_POSITION_TRANSFERRED_OUT = '111',
COLLATERAL_FOR_LIQUIDATION_TRANSFERRED_IN = '112',
COLLATERAL_FOR_LIQUIDATION_TRANSFERRED_OUT = '113',
INSURANCE_FUND_TRANSFERRED_IN = '114',
INSURANCE_FUND_TRANSFERRED_OUT_ = '115',
PLACE_AN_ORDER = '116',
FULFILL_AN_ORDER = '117',
CANCEL_AN_ORDER = '118',
MERCHANTS_UNLOCK_DEPOSIT = '119',
MERCHANTS_ADD_DEPOSIT = '120',
FIATGATEWAY_PLACE_AN_ORDER = '121',
FIATGATEWAY_CANCEL_AN_ORDER = '122',
FIATGATEWAY_FULFILL_AN_ORDER = '123',
JUMPSTART_UNLOCKING = '124',
MANUAL_DEPOSIT = '125',
INTEREST_DEPOSIT = '126',
INVESTMENT_FEE_TRANSFERRED_IN = '127',
INVESTMENT_FEE_TRANSFERRED_OUT = '128',
REWARDS_TRANSFERRED_IN = '129',
TRANSFERRED_FROM_TRADING_ACCOUNT = '130',
TRANSFERRED_TO_TRADING_ACCOUNT = '131',
FROZEN_BY_CUSTOMER_SERVICE = '132',
UNFROZEN_BY_CUSTOMER_SERVICE = '133',
TRANSFERRED_BY_CUSTOMER_SERVICE = '134',
CROSS_CHAIN_EXCHANGE = '135',
CONVERT = '136',
ETH_2_0_SUBSCRIPTION = '137',
ETH_2_0_SWAPPING = '138',
ETH_2_0_EARNINGS = '139',
FEE_TRANSFER_IN = '141',
FEE_TRANSFER_OUT = '142',
SYSTEM_REVERSE = '143',
TRANSFER_OUT_OF_UNIFIED_ACCOUNT_RESERVE = '144',
REWARD_EXPIRED = '145',
CUSTOMER_FEEDBACK = '146',
VESTED_SUSHI_REWARDS = '147',
AFFILIATE_COMMISSION = '150',
REFERRAL_REWARD = '151',
BROKER_REWARD = '152',
JOINER_REWARD = '153',
MYSTERY_BOX_REWARD = '154',
REWARDS_WITHDRAW = '155',
FEE_REBATE_1 = '156',
COLLECTED_CRYPTO = '157',
DUAL_INVESTMENT_SUBSCRIBE = '160',
DUAL_INVESTMENT_COLLECTION = '161',
DUAL_INVESTMENT_PROFIT = '162',
DUAL_INVESTMENT_REFUND = '163',
NEW_YEAR_REWARDS_2022 = '169',
REFERRAL_REFERRED_CUSTOMER = '170',
REFERRAL_WAS_REFERRED = '171',
SUB_AFFILIATE_COMMISSION = '172',
FEE_REBATE_2 = '173',
PAY = '174',
LOCKED_COLLATERAL = '175',
LOAN = '176',
ADDED_COLLATERAL = '177',
RETURNED_COLLATERAL = '178',
REPAYMENT = '179',
UNLOCKED_COLLATERAL = '180',
REPAY_AIRDROPPED_CRYPTO = '181',
FEEDBACK_BOUNTY = '182',
INVITE_FRIENDS_REWARDS = '183',
DIVIDE_THE_REWARD_POOL = '184',
BROKER_CONVERT_REWARD = '185',
FREEETH = '186',
CONVERT_TRANSFER = '187',
SLOT_AUCTION_CONVERSION = '188',
MYSTERY_BOX_BONUS = '189',
CARD_PAYMENT_BUY_1 = '193',
CARD_PAYMENT_BUY_2 = '194',
UNTRADABLE_ASSET_WITHDRAWAL = '195',
UNTRADABLE_ASSET_WITHDRAWAL_REVOKED = '196',
UNTRADABLE_ASSET_DEPOSIT = '197',
UNTRADABLE_ASSET_COLLECTION_1 = '198',
UNTRADABLE_ASSET_COLLECTION_2 = '199',
BUY = '200',
WIN_CRYPTO_WITH_SATOSHI = '211',
}
⋮----
export type AssetBillType = `${ASSET_BILL_TYPE}`;
================
File: src/types/rest/request/convert.ts
================
export interface ConvertQuoteEstimateRequest {
baseCcy: string;
quoteCcy: string;
side: string;
rfqSz: string;
rfqSzCcy: string;
clTReqId?: string;
tag?: string;
}
export interface ConvertTradeRequest {
quoteId: string;
baseCcy: string;
quoteCcy: string;
side: string;
sz: string;
szCcy: string;
clTReqId?: string;
tag?: string;
}
================
File: src/types/rest/request/copy-trading.ts
================
export interface GetCurrentSubpositionsRequest {
instType?: 'SPOT' | 'SWAP';
instId?: string;
uniqueCode?: string;
subPosType?: 'lead' | 'copy';
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface GetSubpositionsHistoryRequest {
instType?: 'SPOT' | 'SWAP';
instId?: string;
subPosType?: 'lead' | 'copy';
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface PlaceCTAlgoOrderRequest {
instType?: 'SPOT' | 'SWAP';
subPosId: string;
tpTriggerPx?: string;
slTriggerPx?: string;
tpOrdPx?: string;
slOrdPx?: string;
tpTriggerPxType?: 'last' | 'index' | 'mark';
slTriggerPxType?: 'last' | 'index' | 'mark';
tag?: string;
subPosType?: 'lead' | 'copy';
}
⋮----
export interface CloseSubpositionRequest {
instType?: 'SPOT' | 'SWAP';
subPosType?: 'lead' | 'copy';
subPosId: string;
ordType?: 'market' | 'limit';
px?: string;
tag?: string;
}
⋮----
export interface GetCTProfitDetailsRequest {
instType?: 'SPOT' | 'SWAP';
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface CopySettingsRequest {
instType?: 'SWAP';
uniqueCode: string;
copyMgnMode: 'cross' | 'isolated' | 'copy';
copyInstIdType: 'custom' | 'copy';
instId?: string;
copyMode?: 'fixed_amount' | 'ratio_copy';
copyTotalAmt: string;
copyAmt?: string;
copyRatio?: string;
tpRatio?: string;
slRatio?: string;
slTotalAmt?: string;
subPosCloseType: 'market_close' | 'copy_close' | 'manual_close';
}
⋮----
export interface GetCTBatchLeverageInfoRequest {
mgnMode: 'cross' | 'isolated';
uniqueCode: string;
instId?: string;
}
⋮----
export interface SetCTBatchLeverageRequest {
mgnMode: 'cross' | 'isolated';
lever: string;
instId: string;
}
⋮----
export interface GetCTHistoryLeadTradersRequest {
instType?: 'SWAP';
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface GetLeadTraderRanksRequest {
instType?: 'SWAP';
sortType?:
| 'overview'
| 'pnl'
| 'aum'
| 'win_ratio'
| 'pnl_ratio'
| 'current_copy_trader_pnl';
state?: '0' | '1';
minLeadDays?: '1' | '2' | '3' | '4';
minAssets?: string;
maxAssets?: string;
minAum?: string;
maxAum?: string;
dataVer?: string;
page?: string;
limit?: string;
}
⋮----
export interface GetLeadTraderStatsRequest {
instType?: 'SWAP';
uniqueCode: string;
lastDays: '1' | '2' | '3' | '4';
}
⋮----
export interface GetLeadTraderPositionsRequest {
instType?: 'SWAP';
uniqueCode: string;
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface GetCopyTradersRequest {
instType?: 'SWAP';
uniqueCode: string;
limit?: string;
}
⋮----
export interface GetPrivateLeadTraderRanksRequest {
instType?: 'SWAP';
sortType?:
| 'overview'
| 'pnl'
| 'aum'
| 'win_ratio'
| 'pnl_ratio'
| 'current_copy_trader_pnl';
state?: '0' | '1';
minLeadDays?: '1' | '2' | '3' | '4';
minAssets?: string;
maxAssets?: string;
minAum?: string;
maxAum?: string;
dataVer?: string;
page?: string;
limit?: string;
}
================
File: src/types/rest/request/grid-trading.ts
================
export type GridAlgoOrderType = 'grid' | 'contract_grid' | 'moon_grid';
⋮----
export interface GetGridAlgoOrdersRequest {
algoOrdType: GridAlgoOrderType;
algoId?: string;
instId?: string;
instType?: 'SPOT' | 'MARGIN' | 'SWAP' | 'FUTURES';
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface GridAlgoTrigger {
triggerAction: 'start' | 'stop';
triggerStrategy: 'instant' | 'price' | 'rsi';
delaySeconds?: string;
timeframe?: '3m' | '5m' | '15m' | '30m' | '1H' | '4H' | '1D';
thold?: string;
triggerCond?: 'cross_up' | 'cross_down' | 'above' | 'below' | 'cross';
timePeriod?: string;
triggerPx?: string;
stopType?: '1' | '2';
}
⋮----
export interface GridAlgoOrderRequest {
instId: string;
algoOrdType: GridAlgoOrderType;
maxPx: string;
minPx: string;
gridNum: string;
runType: '1' | '2';
quoteSz?: string;
baseSz?: string;
sz?: string;
direction?: 'long' | 'short' | 'neutral';
lever?: string;
basePos?: boolean;
tpRatio?: string;
slRatio?: string;
triggerParams?: GridAlgoTrigger[];
}
⋮----
export interface StopGridAlgoOrderRequest {
algoId: string;
instId: string;
algoOrdType: GridAlgoOrderType;
stopType: '1' | '2';
}
⋮----
export interface CloseContractGridPositionRequest {
algoId: string;
mktClose: boolean;
sz?: string;
px?: string;
}
⋮----
export interface GetRSIBackTestingRequest {
instId: string;
timeframe: '3m' | '5m' | '15m' | '30m' | '1H' | '4H' | '1D';
thold: string;
timePeriod: string;
triggerCond?: 'cross_up' | 'cross_down' | 'above' | 'below' | 'cross';
duration?: string;
}
⋮----
export interface MaxGridQuantityRequest {
instId: string;
runType: '1' | '2';
algoOrdType: 'grid' | 'contract_grid';
maxPx: string;
minPx: string;
lever?: string;
}
================
File: src/types/rest/request/public.ts
================
export interface EconomicCalendarRequest {
region?: string;
importance?: '1' | '2' | '3';
before?: string;
after?: string;
limit?: string;
}
⋮----
export interface UnitConvertRequest {
type?: '1' | '2';
instId: string;
sz: string;
px?: string;
unit?: 'coin' | 'usds';
opType: 'open' | 'close';
}
⋮----
export interface CandleRequest {
instId: string;
after?: string;
before?: string;
bar?: string;
limit?: string;
}
⋮----
export interface GetPremiumHistoryRequest {
instId: string;
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface GetContractOpenInterestHistoryRequest {
instId: string;
period?: string;
end?: string;
begin?: string;
limit?: string;
}
⋮----
export interface GetContractTakerVolumeRequest {
instId: string;
period?: string;
unit?: string;
end?: string;
begin?: string;
limit?: string;
}
⋮----
export interface GetTopTradersContractLongShortRatioRequest {
instId: string;
period?: string;
end?: string;
begin?: string;
limit?: string;
}
⋮----
export interface GetOptionTradesRequest {
instId?: string;
instFamily?: string;
optType?: 'C' | 'P';
}
================
File: src/types/rest/request/recurring-buy.ts
================
export interface RecurringBuyInfo {
ccy: string;
ratio: string;
}
⋮----
export interface PlaceRecurringBuyOrderRequest {
stgyName: string;
recurringList: RecurringBuyInfo[];
period: 'monthly' | 'weekly' | 'daily' | 'hourly';
recurringDay?: string;
recurringHour?: string;
recurringTime: string;
timeZone: string;
amt: string;
investmentCcy: 'USDT' | 'USDC';
tdMode: 'cross' | 'cash';
algoClOrdId?: string;
tag?: string;
}
⋮----
export interface AmendRecurringBuyOrderRequest {
algoId: string;
stgyName: string;
}
⋮----
export interface GetRecurringBuyOrderListRequest {
algoId?: string;
after?: string;
before?: string;
limit?: string;
}
================
File: src/types/rest/request/signal-bot.ts
================
export interface CreateSignalRequest {
signalChanName: string;
signalChanDesc?: string;
}
⋮----
export interface GetSignalsRequest {
signalSourceType: string;
signalChanId?: string;
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface EntrySettingParam {
allowMultipleEntry?: string;
entryType?: string;
amt?: string;
ratio?: { ratio: string }[];
}
⋮----
export interface ExitSettingParam {
tpSlType: string;
tpPct?: string;
slPct?: string;
}
⋮----
export interface CreateSignalBotRequest {
signalChanId: string;
lever: string;
investAmt: string;
subOrdType: string;
includeAll?: boolean;
instIds?: string;
ratio?: string;
entrySettingParam?: EntrySettingParam;
exitSettingParam?: ExitSettingParam;
}
⋮----
export interface AdjustMarginBalanceRequest {
algoId: string;
type: 'add' | 'reduce';
amt: string;
allowReinvest?: boolean;
}
⋮----
export interface AmendTPSLRequest {
algoId: string;
exitSettingParam: ExitSettingParam;
}
⋮----
export interface SetSignalInstrumentsRequest {
algoId: string;
instIds: string[];
includeAll: boolean;
}
⋮----
export interface GetSignalBotRequest {
algoOrdType: string;
algoId: string;
after: string;
before?: string;
limit?: string;
}
⋮----
export interface GetSignalBotPositionHistoryRequest {
algoId?: string;
instId?: string;
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface PlaceSubOrderRequest {
instId: string;
algoId: string;
side: 'buy' | 'sell';
ordType: 'market' | 'limit';
sz: string;
px?: string;
reduceOnly?: boolean;
}
⋮----
export interface CancelSubOrderRequest {
algoId: string;
instId: string;
signalOrdId: string;
}
⋮----
export interface GetSignalBotSubOrdersRequest {
algoId: string;
algoOrdType: 'contract';
type?: 'live' | 'filled';
clOrdId?: string;
state?: 'live' | 'partially_filled' | 'filled' | 'cancelled';
signalOrdId?: string;
after?: string;
before?: string;
begin?: string;
end?: string;
limit?: string;
}
⋮----
export interface GetSignalBotEventHistoryRequest {
algoId: string;
after?: string;
before?: string;
limit?: string;
}
================
File: src/types/rest/request/simple-earn.ts
================
export interface GetLendingOrderListRequest {
ordId?: string;
ccy?: string;
term?: '30D';
state?: 'pending' | 'earning' | 'expired' | 'settled';
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface LendingOrder {
ccy: string;
amt: string;
rate?: string;
term: '30D';
autoRenewal?: boolean;
}
⋮----
export interface GetLendingSubOrderListRequest {
ordId: string;
state?: 'earning' | 'expired' | 'settled';
after?: string;
before?: string;
limit?: string;
}
================
File: src/types/rest/request/spread-trading.ts
================
export interface PlaceSpreadOrderRequest {
sprdId: string;
clOrdId?: string;
tag?: string;
side: 'buy' | 'sell';
ordType: 'limit' | 'post_only' | 'ioc' | 'market';
sz: string;
px: string;
}
⋮----
export interface UpdateSpreadOrderRequest {
ordId?: string;
clOrdId?: string;
reqId?: string;
newSz?: string;
newPx?: string;
}
⋮----
export interface GetActiveSpreadOrdersRequest {
sprdId?: string;
ordType?: 'limit' | 'post_only' | 'ioc' | 'market';
state?: 'live' | 'partially_filled';
beginId?: string;
endId?: string;
limit?: string;
}
⋮----
export interface GetSpreadOrderHistoryRequest {
sprdId?: string;
ordType?: 'limit' | 'post_only' | 'ioc' | 'market';
state?: 'canceled' | 'filled';
beginId?: string;
endId?: string;
begin?: string;
end?: string;
limit?: string;
}
⋮----
export interface GetSpreadOrderHistoryArchiveRequest {
sprdId?: string;
ordType?: 'limit' | 'post_only' | 'ioc' | 'market';
state?: 'canceled' | 'filled';
instType?: 'SPOT' | 'FUTURES' | 'SWAP';
instFamily?: string;
beginId?: string;
endId?: string;
begin?: string;
end?: string;
limit?: string;
}
⋮----
export interface GetSpreadTradesRequest {
sprdId?: string;
tradeId?: string;
ordId?: string;
beginId?: string;
endId?: string;
begin?: string;
end?: string;
limit?: string;
}
⋮----
export interface GetSpreadsRequest {
baseCcy?: string;
instId?: string;
sprdId?: string;
state?: 'live' | 'suspend' | 'expired';
}
⋮----
export interface GetSpreadCandlesRequest {
sprdId: string;
bar?: string;
after?: string;
before?: string;
limit?: string;
}
================
File: src/types/rest/request/subaccount.ts
================
type AccountType = '6' | '18';
⋮----
export interface SubAccountTransferRequest {
ccy: string;
amt: string;
from: AccountType;
to: AccountType;
fromSubAccount: string;
toSubAccount: string;
loanTrans?: boolean;
omitPosRisk?: boolean;
}
⋮----
export interface GetSubAccountMaxWithdrawalsRequest {
subAcct: string;
ccy?: string;
}
⋮----
export interface GetManagedSubAccountTransferHistoryRequest {
ccy?: string;
type?: '0' | '1';
subAcct?: string;
subUid?: string;
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface LoanAllocation {
subAcct: string;
loanAlloc: string;
}
⋮----
export interface SetSubAccountLoanAllocationRequest {
enable: boolean;
alloc?: LoanAllocation[];
}
================
File: src/types/rest/response/private-copy-trading.ts
================
export interface CurrentSubposition {
algoId: string;
ccy: string;
instId: string;
instType: string;
lever: string;
margin: string;
markPx: string;
mgnMode: string;
openAvgPx: string;
openOrdId: string;
openTime: string;
posSide: string;
slOrdPx: string;
slTriggerPx: string;
subPos: string;
subPosId: string;
tpOrdPx: string;
tpTriggerPx: string;
uniqueCode: string;
upl: string;
uplRatio: string;
availSubPos: string;
}
⋮----
export interface SubpositionsHistory {
ccy: string;
closeAvgPx: string;
closeTime: string;
instId: string;
instType: string;
lever: string;
margin: string;
markPx: string;
mgnMode: string;
openAvgPx: string;
openOrdId: string;
openTime: string;
pnl: string;
pnlRatio: string;
posSide: string;
profitSharingAmt: string;
subPos: string;
closeSubPos: string;
type: string;
subPosId: string;
uniqueCode: string;
}
⋮----
export interface PlaceCTAlgoOrderResult {
subPosId: string;
tag: string;
}
⋮----
export interface GetCTProfitDetailsResult {
ccy: string;
nickName: string;
profitSharingAmt: string;
profitSharingId: string;
portLink: string;
ts: string;
instType: string;
}
⋮----
export interface GetCTTotalProfitResult {
ccy: string;
totalProfitSharingAmt: string;
instType: string;
}
⋮----
export interface GetCTUnrealizedProfitResult {
ccy: string;
nickName: string;
portLink: string;
ts: string;
unrealizedProfitSharingAmt: string;
instType: string;
}
⋮----
export interface AccountConfigurationDetails {
copyTraderNum: string;
instType: 'SPOT' | 'SWAP';
maxCopyTraderNum: string;
profitSharingRatio: string;
roleType: '0' | '1' | '2';
}
⋮----
export interface GetAccountConfigurationResult {
uniqueCode: string;
nickName: string;
portLink: string;
details: AccountConfigurationDetails[];
}
⋮----
export interface CopySettingsInstId {
instId: string;
enabled: string;
}
⋮----
export interface GetCopySettingsResult {
ccy: string;
copyAmt: string;
copyInstIdType: 'custom' | 'copy';
copyMgnMode: 'cross' | 'isolated' | 'copy';
copyMode: 'fixed_amount' | 'ratio_copy';
copyRatio: string;
copyState: '0' | '1';
copyTotalAmt: string;
instIds: CopySettingsInstId[];
slRatio: string;
slTotalAmt: string;
subPosCloseType: 'market_close' | 'copy_close' | 'manual_close';
tpRatio: string;
}
⋮----
export interface LeverageInfo {
lever: string;
posSide: 'long' | 'short';
}
⋮----
export interface GetCTBatchLeverageInfoResult {
instId: string;
mgnMode: 'cross' | 'isolated';
leadTraderLevers: LeverageInfo[];
myLevers: LeverageInfo[];
}
⋮----
export interface SetCTBatchLeverageResult {
succInstId: string;
failInstId: string;
result: '0' | '1' | '2';
}
⋮----
export interface GetCTMyLeadTradersResult {
portLink: string;
nickName: string;
margin: string;
copyTotalAmt: string;
copyTotalPnl: string;
uniqueCode: string;
ccy: string;
profitSharingRatio: string;
beginCopyTime: string;
upl: string;
todayPnl: string;
leadMode: 'public' | 'private';
}
⋮----
export interface GetCTHistoryLeadTradersResult {
portLink: string;
nickName: string;
uniqueCode: string;
copyNum: string;
copyTotalAmt: string;
copyTotalPnl: string;
copyAmt: string;
copyMode: 'fixed_amount' | 'ratio_copy';
copyRatio: string;
ccy: string;
profitSharingRatio: string;
beginCopyTime: string;
endCopyTime: string;
copyRelId: string;
copyState: '0' | '1';
leadMode: 'public' | 'private';
}
⋮----
export interface GetCopyTradingConfigResult {
maxCopyAmt: string;
minCopyAmt: string;
maxCopyTotalAmt: string;
minCopyRatio: string;
maxCopyRatio: string;
maxTpRatio: string;
maxSlRatio: string;
}
⋮----
export interface PnlRatio {
beginTs: string;
pnlRatio: string;
}
⋮----
export interface LeadTraderRank {
accCopyTraderNum: string;
aum: string;
ccy: string;
copyState: '0' | '1';
copyTraderNum: string;
leadDays: string;
maxCopyTraderNum: string;
nickName: string;
pnl: string;
pnlRatio: string;
pnlRatios: PnlRatio[];
portLink: string;
traderInsts: string[];
uniqueCode: string;
winRatio: string;
}
⋮----
export interface GetLeadTraderRanksResult {
dataVer: string;
ranks: LeadTraderRank[];
totalPage: string;
}
⋮----
export interface LeadTraderPnl {
beginTs: string;
pnl: string;
pnlRatio: string;
}
⋮----
export interface LeadTraderStats {
avgSubPosNotional: string;
ccy: string;
curCopyTraderPnl: string;
investAmt: string;
lossDays: string;
profitDays: string;
winRatio: string;
}
⋮----
export interface LeadTraderPreference {
ccy: string;
ratio: string;
}
⋮----
export interface LeadTraderCurrentPosition {
ccy: string;
instId: string;
instType: string;
lever: string;
margin: string;
markPx: string;
mgnMode: string;
openAvgPx: string;
openTime: string;
posSide: string;
subPos: string;
subPosId: string;
uniqueCode: string;
upl: string;
uplRatio: string;
}
⋮----
export interface LeadTraderPositionHistory {
ccy: string;
closeAvgPx: string;
closeTime: string;
instId: string;
instType: string;
lever: string;
margin: string;
mgnMode: string;
openAvgPx: string;
openTime: string;
pnl: string;
pnlRatio: string;
posSide: string;
subPos: string;
subPosId: string;
uniqueCode: string;
}
⋮----
export interface CopyTraderInfo {
beginCopyTime: string;
nickName: string;
portLink: string;
pnl: string;
}
⋮----
export interface GetCopyTradersResult {
copyTotalPnl: string;
ccy: string;
copyTraderNumChg: string;
copyTraderNumChgRatio: string;
copyTraders: CopyTraderInfo[];
}
⋮----
export interface GetPrivateLeadTraderRanksResult {
dataVer: string;
chanType: 'OKX' | 'ND';
ranks: LeadTraderRank[];
totalPage: string;
}
================
File: src/types/rest/response/private-flexible-loan.ts
================
export interface CollateralAsset {
ccy: string;
amt: string;
notionalUsd: string;
}
⋮----
export interface CollateralAssetsResponse {
assets: CollateralAsset[];
}
⋮----
export interface SupplementaryCollateral {
ccy: string;
amt: string;
}
⋮----
export interface MaxLoanRequest {
borrowCcy: string;
supCollateral?: SupplementaryCollateral[];
}
⋮----
export interface MaxLoanResponse {
borrowCcy: string;
maxLoan: string;
notionalUsd: string;
remainingQuota: string;
}
⋮----
export interface AdjustCollateralRequest {
type: 'add' | 'reduce';
collateralCcy: string;
collateralAmt: string;
}
⋮----
export interface LoanCurrencyData {
ccy: string;
amt: string;
}
⋮----
export interface RiskWarningData {
instId: string;
liqPx: string;
}
⋮----
export interface LoanInfo {
loanNotionalUsd: string;
loanData: LoanCurrencyData[];
collateralNotionalUsd: string;
collateralData: LoanCurrencyData[];
riskWarningData: RiskWarningData;
curLTV: string;
marginCallLTV: string;
liqLTV: string;
}
⋮----
export interface LoanHistoryRequest {
type?:
| 'borrowed'
| 'repaid'
| 'collateral_locked'
| 'collateral_released'
| 'forced_repayment_buy'
| 'forced_repayment_sell'
| 'forced_liquidation'
| 'partial_liquidation';
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface LoanHistoryItem {
refId: string;
type: string;
ccy: string;
amt: string;
ts: string;
}
⋮----
export interface AccruedInterestRequest {
ccy?: string;
after?: string;
before?: string;
limit?: string;
}
⋮----
export interface AccruedInterestItem {
refId: string;
ccy: string;
loan: string;
interest: string;
interestRate: string;
ts: string;
}
================
File: src/types/rest/response/private-recurring-buy.ts
================
export interface RecurringBuyOrderResult {
algoId: string;
algoClOrdId: string;
sCode: string;
sMsg: string;
}
⋮----
export interface RecurringBuyInfoResult {
ccy: string;
ratio: string;
}
⋮----
export interface RecurringBuyOrder {
algoId: string;
algoClOrdId: string;
instType: string;
cTime: string;
uTime: string;
algoOrdType: 'recurring';
state: 'running' | 'stopping' | 'pause';
stgyName: string;
recurringList: RecurringBuyInfoResult[];
period: 'monthly' | 'weekly' | 'daily' | 'hourly';
recurringDay?: string;
recurringHour?: string;
recurringTime: string;
timeZone: string;
amt: string;
investmentAmt: string;
investmentCcy: 'USDT' | 'USDC';
totalPnl: string;
totalAnnRate: string;
pnlRatio: string;
mktCap: string;
cycles: string;
tag: string;
}
⋮----
export interface RecurringBuyInfoOrder {
ccy: string;
ratio: string;
totalAmt: string;
profit: string;
avgPx: string;
px: string;
}
⋮----
export interface RecurringBuySubOrder {
algoId: string;
instType: string;
instId: string;
algoOrdType: 'recurring';
ordId: string;
cTime: string;
uTime: string;
tdMode: 'cross' | 'cash';
ordType: 'market';
sz: string;
state: 'canceled' | 'live' | 'partially_filled' | 'filled' | 'cancelling';
side: 'buy' | 'sell';
px: string;
fee: string;
feeCcy: string;
avgPx: string;
accFillSz: string;
tag: string;
}
================
File: src/types/rest/response/private-signal-bot.ts
================
export interface CreateSignalResult {
signalChanId: string;
signalToken: string;
}
⋮----
export interface GetSignalsResult {
signalChanId: string;
signalChanName: string;
signalChanDesc: string;
signalChanToken: string;
signalSourceType: string;
}
⋮----
export interface CreateSignalBotResult {
algoId: string;
algoClOrdId: string;
sCode: string;
sMsg: string;
}
⋮----
export interface CancelSignalBotsResult {
algoId: string;
sCode: string;
sMsg: string;
}
================
File: src/types/rest/response/private-spread-trading.ts
================
export interface PlaceSpreadOrderResponse {
ordId: string;
clOrdId: string;
tag: string;
sCode: string;
sMsg: string;
}
⋮----
export interface CancelSpreadOrderResponse {
ordId: string;
clOrdId: string;
sCode: string;
sMsg: string;
}
⋮----
export interface UpdateSpreadOrderResponse {
ordId: string;
clOrdId: string;
reqId: string;
sCode: string;
sMsg: string;
}
⋮----
export interface SpreadOrder {
instId: string;
ordId: string;
clOrdId: string;
tag: string;
px: string;
sz: string;
ordType: 'limit' | 'post_only' | 'ioc';
side: 'buy' | 'sell';
fillSz: string;
fillPx: string;
tradeId: string;
accFillSz: string;
pendingFillSz: string;
pendingSettleSz: string;
canceledSz: string;
avgPx: string;
state: 'canceled' | 'live' | 'partially_filled' | 'filled';
cancelSource: string;
uTime: string;
cTime: string;
}
⋮----
export interface SpreadTradeLeg {
instId: string;
px: string;
sz: string;
side: 'buy' | 'sell';
fee: string;
szCont: string;
feeCcy: string;
tradeId: string;
}
⋮----
export interface SpreadTrade {
sprdId: string;
tradeId: string;
ordId: string;
clOrdId: string;
tag: string;
fillPx: string;
fillSz: string;
side: 'buy' | 'sell';
state: 'filled' | 'rejected';
execType: 'T' | 'M';
ts: string;
legs: SpreadTradeLeg[];
}
⋮----
export interface SpreadLeg {
instId: string;
side: 'buy' | 'sell';
}
⋮----
export interface SpreadDetails {
sprdId: string;
sprdType: 'linear' | 'inverse' | 'hybrid';
state: 'live' | 'expired' | 'suspend';
baseCcy: string;
szCcy: string;
quoteCcy: string;
tickSz: string;
minSz: string;
lotSz: string;
listTime: string;
expTime: string;
uTime: string;
legs: SpreadLeg[];
}
⋮----
export interface OrderBookEntry {
price: string;
quantity: string;
orderCount: string;
}
⋮----
export interface SpreadOrderBook {
asks: OrderBookEntry[];
bids: OrderBookEntry[];
ts: string;
}
⋮----
export interface SpreadTicker {
sprdId: string;
last: string;
lastSz: string;
askPx: string;
askSz: string;
bidPx: string;
bidSz: string;
open24h: string;
high24h: string;
low24h: string;
vol24h: string;
ts: string;
}
⋮----
export interface PublicSpreadTrade {
sprdId: string;
tradeId: string;
px: string;
sz: string;
side: 'buy' | 'sell';
ts: string;
}
⋮----
export interface SpreadCandle {
ts: string;
o: string;
h: string;
l: string;
c: string;
vol: string;
confirm: string;
}
================
File: src/types/rest/response/private-subaccount.ts
================
export interface SubAccount {
enable: boolean;
subAcct: string;
type: string;
label: string;
mobile: string;
gAuth: boolean;
canTransOut: boolean;
ts: string;
}
⋮----
export interface SubAccountAPIReset {
subAcct: string;
label: string;
apiKey: string;
perm: string;
ip: string;
ts: string;
}
⋮----
export interface SubAccountBalanceDetail {
availBal: string;
availEq: string;
cashBal: string;
ccy: string;
crossLiab: string;
disEq: string;
eq: string;
eqUsd: string;
frozenBal: string;
interest: string;
isoEq: string;
isoLiab: string;
liab: string;
maxLoan: string;
mgnRatio: string;
notionalLever: string;
ordFrozen: string;
twap: string;
uTime: string;
upl: string;
uplLiab: string;
spotBal: string; // Spot balance. The unit is currency, e.g. BTC.
openAvgPx: string[]; // Spot average cost price. The unit is USD.
accAvgPx: string[]; // Spot accumulated cost price. The unit is USD.
spotUpl: string; // Spot unrealized profit and loss. The unit is USD.
spotUplRatio: string; // Spot unrealized profit and loss ratio.
totalPnl: string; // Spot accumulated profit and loss. The unit is USD.
totalPnlRatio: string; // Spot accumulated profit and loss ratio.
}
⋮----
spotBal: string; // Spot balance. The unit is currency, e.g. BTC.
openAvgPx: string[]; // Spot average cost price. The unit is USD.
accAvgPx: string[]; // Spot accumulated cost price. The unit is USD.
spotUpl: string; // Spot unrealized profit and loss. The unit is USD.
spotUplRatio: string; // Spot unrealized profit and loss ratio.
totalPnl: string; // Spot accumulated profit and loss. The unit is USD.
totalPnlRatio: string; // Spot accumulated profit and loss ratio.
⋮----
export interface SubAccountBalances {
adjEq: string;
details: SubAccountBalanceDetail[];
imr: string;
isoEq: string;
mgnRatio: string;
mmr: string;
notionalUsd: string;
ordFroz: string;
totalEq: string;
uTime: string;
spotCopyTradingEq: string;
}
⋮----
export interface SubAccountTransferResult {
transId: string;
}
⋮----
export interface SubAccountMaxWithdrawal {
ccy: string;
maxWd: string;
maxWdEx: string;
spotOffsetMaxWd: string;
spotOffsetMaxWdEx: string;
}
⋮----
export interface ManagedSubAccountTransfer {
billId: string;
ccy: string;
amt: string;
type: string;
subAcct: string;
subUid: string;
ts: string;
}
================
File: webpack/webpack.config.js
================
function generateConfig(name)
⋮----
// Add '.ts' and '.tsx' as resolvable extensions.
⋮----
// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
⋮----
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
================
File: .jshintrc
================
{
"esversion": 8,
"asi": true,
"laxbreak": true,
"predef": [ "-Promise" ]
}
================
File: .nvmrc
================
v22.17.1
================
File: LICENSE.md
================
Copyright 2022 Tiago Siebler
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================
File: examples/auth/fasterHmacSign.ts
================
import { createHmac } from 'crypto';
⋮----
import { DefaultLogger, RestClient, WebsocketClient } from '../../src/';
⋮----
// or
// import { createHmac } from 'crypto';
// import { DefaultLogger, RestClient, WebsocketClient } from 'okx-api';
⋮----
/**
* Injecting a custom signMessage function.
*
* As of version 3.0.0 of the okx-api Node.js/TypeScript/JavaScript
* SDK for OKX, the SDK uses the Web Crypto API for signing requests.
* While it is compatible with Node and Browser environments, it is
* slightly slower than using Node's native crypto module (only
* available in backend Node environments).
*
* For latency sensitive users, you can inject the previous node crypto sign
* method (or your own even faster implementation), if this change affects you.
*
* This example demonstrates how to inject a custom sign function, to achieve
* the same peformance as seen before the Web Crypto API was introduced.
*
* For context on standard usage, the "signMessage" function is used:
* - During every single API call
* - After opening a new private WebSocket connection
*/
⋮----
// If running from CLI in unix, you can pass env vars as such:
// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-private-trade.ts
⋮----
// note the single quotes, preventing special characters such as $ from being incorrectly passed
⋮----
// apiKey: 'apiKeyHere',
⋮----
// apiSecret: 'apiSecretHere',
⋮----
// apiPass: 'apiPassHere',
/**
* Overkill in almost every case, but if you need any optimisation available,
* you can inject a faster sign mechanism such as node's native createHmac:
*/
⋮----
// Optional, uncomment the "trace" override to log a lot more info about what the WS client is doing
⋮----
// trace: (...params) => console.log('trace', ...params),
⋮----
// For private topics, include one or more accounts in an array. Otherwise only public topics will work
⋮----
/**
* Overkill in almost every case, but if you need any optimisation available,
* you can inject a faster sign mechanism such as node's native createHmac:
*/
⋮----
function setWsClientEventListeners(
websocketClient: WebsocketClient,
accountRef: string,
): Promise<void>
⋮----
// console.log('raw message received ', JSON.stringify(data, null, 2));
⋮----
// Simple promise to ensure we're subscribed before trying anything else
⋮----
// Start trading
================
File: examples/demo-trading.ts
================
import { RestClient, WebsocketClient } from '../src/index';
⋮----
// or
// import { RestClient} from 'okx-api';
⋮----
// read from environmental variables, your demo trading keys
⋮----
// okx api credentials
⋮----
// Raw data will arrive on the 'update' event
⋮----
// console.log('ws update (raw data received)', JSON.stringify(data, null, 2));
⋮----
// Replies (e.g. authenticating or subscribing to channels) will arrive on the 'response' event
⋮----
// console.log('ws response: ', JSON.stringify(data, null, 2));
⋮----
// Subscribe to demo account events:
⋮----
/** Simple examples for private REST API calls with bybit's V5 REST APIs */
⋮----
// Trade USDT linear perps
================
File: examples/rest-private-trade.ts
================
/* eslint-disable @typescript-eslint/no-unused-vars */
import { RestClient } from '../src/index.js';
import { OrderRequest } from '../src/types/rest/request/trade.js';
⋮----
// or
// import { SpotClient } from 'okx-api';
⋮----
// read from environmental variables
⋮----
// If running from CLI in unix, you can pass env vars as such:
// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-private-trade.ts
⋮----
// note the single quotes, preventing special characters such as $ from being incorrectly passed
⋮----
// apiKey: 'apiKeyHere',
⋮----
// apiSecret: 'apiSecretHere',
⋮----
// apiPass: 'apiPassHere',
⋮----
// const wsClient = new WebsocketClient({
// apiKey: API_KEY,
// apiSecret: API_SECRET,
// apiPass: API_PASS,
// });
⋮----
function logWSEvent(type, data)
⋮----
// simple sleep function
function promiseSleep(milliseconds)
⋮----
// WARNING: for sensitive math you should be using a library such as decimal.js!
function roundDown(value, decimals)
⋮----
/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */
⋮----
// // Add event listeners to log websocket events on account
// wsClient.on('update', (data) => logWSEvent('update', data));
// wsClient.on('open', (data) => logWSEvent('open', data));
// wsClient.on('response', (data) => logWSEvent('response', data));
// wsClient.on('reconnect', (data) => logWSEvent('reconnect', data));
// wsClient.on('reconnected', (data) => logWSEvent('reconnected', data));
// wsClient.on('authenticated', (data) => logWSEvent('authenticated', data));
// wsClient.on('exception', (data) => logWSEvent('exception', data));
⋮----
// // Subscribe to private account topics
// wsClient.subscribeTopic('SPBL', 'account');
// wsClient.subscribeTopic('SPBL', 'orders');
⋮----
// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting)
⋮----
// const balances = allBalances.filter((bal) => Number(bal.available) != 0);
⋮----
// console.log('balance: ', JSON.stringify(balances, null, 2));
⋮----
// example to find minimum allowed size for a symbol and place an order with it
/* const symbol = 'BTC-USDT-SWAP';
const symbolsResult = await client.getInstruments({
instType: 'SWAP',
});
const btcRules = symbolsResult.find((rule) => rule.instId === symbol);
console.log('btc trading rules: ', btcRules);
if (!btcRules) {
return console.log('no rules found for trading ' + symbol);
}
const minSize = Number(btcRules.minSz);
const order = {
instId: symbol,
tdMode: 'cross',
ordType: 'market',
side: 'sell',
sz: String(minSize),
} as const;
console.log('submitting order: ', order);
const sellResult = await client.submitOrder(order);
console.log('sell result: ', sellResult); */
================
File: examples/ws-api-client.ts
================
import { DefaultLogger, WebsocketAPIClient } from '../src';
⋮----
// or use the module installed via `npm install okx-api`:
// import { WebsocketClient, DefaultLogger } from 'okx-api';
⋮----
// or if you're not using typescript (e.g. pure nodejs), change the "import" to "require":
// const { WebsocketClient, DefaultLogger } = require('okx-api');
⋮----
// function attachEventHandlers<TWSClient extends WebsocketClient>(
// wsClient: TWSClient,
// ): void {
// wsClient.on('update', (data) => {
// console.log('raw message received ', JSON.stringify(data));
// });
// wsClient.on('open', (data) => {
// console.log('ws connected', data.wsKey);
// });
// wsClient.on('reconnect', ({ wsKey }) => {
// console.log('ws automatically reconnecting.... ', wsKey);
// });
// wsClient.on('reconnected', (data) => {
// console.log('ws has reconnected ', data?.wsKey);
// });
// wsClient.on('authenticated', (data) => {
// console.log('ws has authenticated ', data?.wsKey);
// });
// }
⋮----
// For private events, all 3 of the following are required (per account):
⋮----
// If running from CLI in unix, you can pass env vars as such:
// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts
⋮----
// For Global users (www.okx.com), you don't need to set the market.
// It will use global by default.
// Not needed: market: 'GLOBAL',
⋮----
// For EEA users (my.okx.com), set market to "EEA":
// market: 'EEA',
⋮----
// For US users (app.okx.com), set market to "US":
// market: 'US',
⋮----
// For private topics, include one or more accounts in an array. Otherwise only public topics will work
⋮----
// Optional, see above "attachEventListeners". Attach basic event handlers, so nothing is left unhandled
// attachEventHandlers(wsClient.getWSClient());
⋮----
// Optional: prepare the WebSocket API connection in advance.
// This happens automatically but you can do this early before making any API calls, to prevent delays from a cold start.
// await wsClient.connectWSAPI();
⋮----
/**
* OKX's WebSocket API be used like a REST API, through this SDK's WebsocketAPIClient. The WebsocketAPIClient is a utility class wrapped around WebsocketClient's sendWSAPIRequest() capabilities.
*
* Each request sent via the WebsocketAPIClient will automatically:
* - route via the active WS API connection
* - return a Promise, which automatically resolves/rejects when a matching response is received
*/
⋮----
/**
* Place Order
* https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-place-order
*/
⋮----
/**
const res = {
id: '2',
op: 'order',
code: '1',
msg: '',
data: [
{
tag: '159881cb7207BCDE',
ts: '1753714603721',
ordId: '',
clOrdId: '',
sCode: '51008',
sMsg: 'Order failed. Insufficient USDT balance in account.'
}
],
inTime: '1753714603720755',
outTime: '1753714603721942',
wsKey: 'prodPrivate',
isWSAPIResponse: false
}
const res = {
id: '2',
op: 'order',
code: '1',
msg: '',
data: [
{
tag: '159881cb7207BCDE',
ts: '1753714567149',
ordId: '',
clOrdId: '',
sCode: '51010',
sMsg: "You can't complete this request under your current account mode."
}
],
inTime: '1753714567149196',
outTime: '1753714567149913',
wsKey: 'prodPrivate',
isWSAPIResponse: false
}
*/
⋮----
/**
* Submit multiple orders in a batch
* https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-place-multiple-orders
*/
================
File: examples/ws-api-trade-raw.ts
================
// If you cloned the repo and are using typescript, you can import from src directly:
import { DefaultLo