okx-api
Version:
Complete Node.js SDK for OKX's REST APIs and WebSockets, with TypeScript & end-to-end tests
1,995 lines (1,946 loc) • 307 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/, dist/, lib/
- 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
Rest/
app.okx.com.ts
demo-trading.ts
my.okx.com.ts
rest-private-trade-market.ts
rest-private-trade.ts
rest-public.ts
Websocket/
WS-API/
ws-api-client.ts
ws-api-trade-raw.ts
app.okx.com.ts
ws-private-handle-auth-fail.ts
ws-private.ts
ws-public.ts
README.md
src/
constants/
funding.ts
types/
rest/
request/
account.ts
affiliate.ts
block-trading.ts
convert.ts
copy-trading.ts
dual-investment.ts
funding.ts
grid-trading.ts
public.ts
recurring-buy.ts
shared.ts
signal-bot.ts
simple-earn.ts
spread-trading.ts
stable-rewards.ts
subaccount.ts
trade.ts
response/
private-account.ts
private-affiliate.ts
private-block-trading.ts
private-copy-trading.ts
private-dual-investment.ts
private-flexible-loan.ts
private-funding.ts
private-recurring-buy.ts
private-signal-bot.ts
private-spread-trading.ts
private-stable-rewards.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.cjs
.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: 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/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/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/shared.ts
================
import { numberInString } from '../shared.js';
⋮----
export interface PaginatedSymbolRequest {
ccy?: string;
after?: numberInString;
before?: numberInString;
limit?: numberInString;
}
================
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-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: .eslintrc.cjs
================
'require-extensions', // only once moved to ESM
⋮----
'plugin:require-extensions/recommended', // only once moved to ESM
⋮----
// 'no-unused-vars': ['warn'],
================
File: .jshintrc
================
{
"esversion": 8,
"asi": true,
"laxbreak": true,
"predef": [ "-Promise" ]
}
================
File: .nvmrc
================
v22.17.1
================
File: .prettierrc
================
{
"tabWidth": 2,
"singleQuote": true,
"trailingComma": "all"
}
================
File: jest.config.ts
================
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
⋮----
import type { Config } from 'jest';
⋮----
// All imported modules in your tests should be mocked automatically
// automock: false,
⋮----
// Stop running tests after `n` failures
// bail: 0,
bail: false, // enable to stop test when an error occur,
⋮----
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx",
⋮----
// Automatically clear mock calls, instances, contexts and results before every test
⋮----
// Indicates whether the coverage information should be collected while executing the test
⋮----
// An array of glob patterns indicating a set of files for which coverage information should be collected
⋮----
// The directory where Jest should output its coverage files
⋮----
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
⋮----
// Indicates which provider should be used to instrument code for coverage
⋮----
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
⋮----
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
⋮----
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
⋮----
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
⋮----
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
⋮----
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
⋮----
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
⋮----
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
⋮----
// A set of global variables that need to be available in all test environments
// globals: {},
⋮----
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
⋮----
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
⋮----
// An array of file extensions your modules use
⋮----
// modulePaths: ['src'],
⋮----
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
⋮----
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
⋮----
// Activates notifications for test results
// notify: false,
⋮----
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
⋮----
// A preset that is used as a base for Jest's configuration
// preset: undefined,
⋮----
// Run tests from one or more projects
// projects: undefined,
⋮----
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
⋮----
// Automatically reset mock state before every test
// resetMocks: false,
⋮----
// Reset the module registry before running each individual test
// resetModules: false,
⋮----
// A path to a custom resolver
// resolver: undefined,
⋮----
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
⋮----
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
⋮----
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
⋮----
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
⋮----
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
⋮----
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
⋮----
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
⋮----
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
⋮----
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
⋮----
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
⋮----
// Adds a location field to test results
// testLocationInResults: false,
⋮----
// The glob patterns Jest uses to detect test files
⋮----
// "**/__tests__/**/*.[jt]s?(x)",
⋮----
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
⋮----
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
⋮----
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
⋮----
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
⋮----
// A map from regular expressions to paths to transformers
// transform: undefined,
⋮----
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
⋮----
// Prevents import esm module error from v1 axios release, issue #5026
⋮----
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
⋮----
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
verbose: true, // report individual test
⋮----
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
⋮----
// Whether to use watchman for file crawling
// watchman: true,
================
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: postBuild.sh
================
#!/bin/bash
#
# Add package.json files to cjs/mjs subtrees
#
cat >dist/cjs/package.json <<!EOF
{
"type": "commonjs"
}
!EOF
cat >dist/mjs/package.json <<!EOF
{
"type": "module"
}
!EOF
find src -name '*.d.ts' -exec cp {} dist/mjs \;
find src -name '*.d.ts' -exec cp {} dist/cjs \;
================
File: tsconfig.cjs.json
================
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "dist/cjs",
"target": "esnext"
},
"include": ["src/**/*.*"]
}
================
File: tsconfig.esm.json
================
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "esnext",
"outDir": "dist/mjs",
"target": "esnext"
},
"include": ["src/**/*.*"]
}
================
File: tsconfig.json
================
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"noEmitOnError": true,
"declaration": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": false,
"inlineSourceMap": false,
"lib": ["esnext", "DOM"],
"listEmittedFiles": false,
"listFiles": false,
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noUnusedParameters": true,
"pretty": true,
"removeComments": false,
"resolveJsonModule": true,
"skipLibCheck": false,
"sourceMap": true,
"strict": true,
"strictNullChecks": true,
"types": ["node", "jest"],
"module": "CommonJS",
"outDir": "dist/cjs",
"target": "ESNext"
},
"compileOnSave": true,
"include": ["src/**/*.*", "test/**/*.*", ".eslintrc.cjs"],
"exclude": ["node_modules", "**/node_modules/*", "coverage", "doc", "dist"]
}
================
File: tsconfig.linting.json
================
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"target": "esnext",
"rootDir": "../",
"allowJs": true
},
"include": [
"src/**/*.*",
"test/**/*.*",
"examples/**/*.*",
".eslintrc.cjs",
"jest.config.ts",
"webpack/webpack.config.ts"
]
}
================
File: examples/Rest/app.okx.com.ts
================
import { RestClient, WebsocketClient } from '../../src/index.js';
⋮----
// or
// import { RestClient } from 'okx-api';
⋮----
/**
* To use "app.okx.com", set market to "US"
*
* Note: your available functionality may differ, refer to the corresponding API docs for more details:
* https://app.okx.com/docs-v5/en/#overview-production-trading-services
*/
⋮----
/**
* This is a simple script wrapped in a immediately invoked function expression, designed to make public API calls without credentials
*/
⋮----
// Raw data will arrive on the 'update' event
⋮----
// console.log(
// new Date(),
// 'ws update (raw data received)',
// JSON.stringify(data, null, 2),
// );
// console.log('ws update (raw data received)', JSON.stringify(data, null, 2));
================
File: examples/Rest/demo-trading.ts
================
import { RestClient, WebsocketClient } from '../../src/index.js';
⋮----
// 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/my.okx.com.ts
================
import { RestClient, WebsocketClient } from '../../src/index.js';
⋮----
// or
// import { RestClient } from 'okx-api';
⋮----
/**
* To use "my.okx.com", set market to "EEA"
*
* Note: your available functionality may differ, refer to the corresponding API docs for more details:
* https://my.okx.com/docs-v5/en/#overview-production-trading-services
*/
⋮----
async function start()
⋮----
// Raw data will arrive on the 'update' event
⋮----
// console.log(
// new Date(),
// 'ws update (raw data received)',
// JSON.stringify(data, null, 2),
// );
// console.log('ws update (raw data received)', JSON.stringify(data, null, 2));
================
File: examples/Rest/rest-private-trade-market.ts
================
import { OrderRequest, RestClient } from '../../src/index.js';
⋮----
// 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/rest-public.ts
================
import { RestClient } from '../../src/index.js';
⋮----
// 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: examples/Websocket/app.okx.com.ts
================
import { RestClient, WebsocketClient } from '../../src/index.js';
⋮----
// or
// import { RestClient } from 'okx-api';
⋮----
/**
* To use "app.okx.com", set market to "US"
*
* Note: your available functionality may differ, refer to the corresponding API docs for more details:
* https://app.okx.com/docs-v5/en/#overview-production-trading-services
*/
⋮----
/**
* This is a simple script wrapped in a immediately invoked function expression, designed to make public API calls without credentials
*/
⋮----
// Raw data will arrive on the 'update' event
⋮----
// console.log(
// new Date(),
// 'ws update (raw data received)',
// JSON.stringify(data, null, 2),
// );
// console.log('ws update (raw data received)', JSON.stringify(data, null, 2));
================
File: examples/Websocket/ws-private-handle-auth-fail.ts
================
// If you cloned the repo and are using typescript, you can import from src directly:
import { WebsocketClient } from '../../src/index.js';
⋮----
/**
*
* This simple example demonstrates one way to handle failed authentication, stopping the
* websocket client from running into a reconnect-loop when authentication fails (e.g. bad API keys).
*
* However, keep in mind it might be safer to make a test REST API call (e.g. fetch account balance) before
* trying to make a private WS connection to the account.
*
*/
⋮----
// For private topics, include one or more accounts in an array. Otherwise only public topics will work
⋮----
// 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));
⋮----
// Optional, connect before subscribing:
⋮----
// This is optional though. The wsclient will automatically open and subscribe if the connection doesn't exist yet.
⋮----
// Subscribe one event at a time:
================
File: examples/Websocket/ws-private.ts
================
// If you cloned the repo and are using typescript, you can import from src directly:
import { DefaultLogger, WebsocketClient } from '../../src/index.js';
⋮----
// 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