Skip to content

Commit a1af566

Browse files
committed
fix static tests
1 parent 75cfe64 commit a1af566

3 files changed

Lines changed: 174 additions & 22 deletions

File tree

src/node-binance-api.ts

Lines changed: 40 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ import zip from 'lodash.zipobject'
1515
import stringHash from 'string-hash';
1616
import async from 'async';
1717

18-
import {Interval, PositionRisk, Order, FuturesOrder, PositionSide, WorkingType, OrderType, OrderStatus, TimeInForce, Callback, IConstructorArgs, OrderSide, FundingRate, CancelOrder, AggregatedTrade, Trade, MyTrade, WithdrawHistoryResponse, DepositHistoryResponse, DepositAddress, WithdrawResponse, Candle, FuturesCancelAllOpenOrder, OrderBook, Ticker, FuturesUserTrade, Account, FuturesAccountInfo, FuturesBalance} from './types'
19-
export {Interval, PositionRisk, Order, FuturesOrder, PositionSide, WorkingType, OrderType, OrderStatus, TimeInForce, Callback, IConstructorArgs} from './types'
18+
import {Interval, PositionRisk, Order, FuturesOrder, PositionSide, WorkingType, OrderType, OrderStatus, TimeInForce, Callback, IConstructorArgs, OrderSide, FundingRate, CancelOrder, AggregatedTrade, Trade, MyTrade, WithdrawHistoryResponse, DepositHistoryResponse, DepositAddress, WithdrawResponse, Candle, FuturesCancelAllOpenOrder, OrderBook, Ticker, FuturesUserTrade, Account, FuturesAccountInfo, FuturesBalance, QueryOrder} from './types'
19+
// export {Interval, PositionRisk, Order, FuturesOrder, PositionSide, WorkingType, OrderType, OrderStatus, TimeInForce, Callback, IConstructorArgs} from './types'
2020

2121
export interface Dictionary<T> {
2222
[key: string]: T;
@@ -111,8 +111,9 @@ export default class Binance {
111111
}
112112

113113
options(opt = {}, callback: any = false): Binance {
114-
// return await this.setOptions(opt, callback); // keep this method for backwards compatibility
115-
this.assignOptions(opt, callback);
114+
// // return await this.setOptions(opt, callback); // keep this method for backwards compatibility
115+
// this.assignOptions(opt, callback);
116+
this.setOptions(opt, callback);
116117
return this;
117118
}
118119

@@ -160,6 +161,7 @@ export default class Binance {
160161
if (this.Options.useServerTime) {
161162

162163
const res = await this.publicRequest(this.getSpotUrl() + 'v3/time');
164+
console.log(res)
163165
this.info.timeOffset = res.serverTime - new Date().getTime();
164166

165167
}
@@ -268,7 +270,7 @@ export default class Binance {
268270
reqOptions.body = urlBody;
269271
} else {
270272
if (opt.qs) {
271-
opt.url += '?' + this.makeQueryString(opt.qs);
273+
// opt.url += '?' + this.makeQueryString(opt.qs);
272274
}
273275
}
274276
const response = await fetch(opt.url, reqOptions)
@@ -315,7 +317,8 @@ export default class Binance {
315317
}
316318

317319
async publicRequest(url: string, data: Dict = {}, method = 'GET') {
318-
let opt = this.reqObj(url, data, method);
320+
const query = this.makeQueryString(data);
321+
const opt = this.reqObj(url + (query ? '?' + query : ''), data, method);
319322
const res = await this.proxyRequest(opt);
320323
return res;
321324
};
@@ -344,6 +347,10 @@ export default class Binance {
344347
timeout: this.Options.recvWindow,
345348
followAllRedirects: true
346349
};
350+
query = this.makeQueryString(data);
351+
if (flags.method === 'GET') {
352+
opt.url = `${baseURL}${url}?${query}`;
353+
}
347354
if (flags.type === 'SIGNED' || flags.type === 'TRADE' || flags.type === 'USER_DATA') {
348355
data.timestamp = new Date().getTime();
349356
if (this.info.timeOffset) {
@@ -690,7 +697,7 @@ export default class Binance {
690697
* @param {string} symbol - the symbol to get
691698
* @return {promise or undefined} - omitting the callback returns a promise
692699
*/
693-
async openOrders(symbol?: string, params: Dict = {}) {
700+
async openOrders(symbol?: string, params: Dict = {}): Promise<QueryOrder[]> {
694701
const parameters = symbol ? { symbol: symbol } : {};
695702
return await this.signedRequest(this.getSpotUrl() + 'v3/openOrders', this.extend(parameters, params));
696703
}
@@ -736,7 +743,7 @@ export default class Binance {
736743
* @param {object} options - additional options
737744
* @return {promise or undefined} - omitting the callback returns a promise
738745
*/
739-
async allOrders(symbol: string, params: Dict = {}) {
746+
async allOrders(symbol: string, params: Dict = {}): Promise<QueryOrder[]> {
740747
let parameters = this.extend({ symbol }, params);
741748
return await this.signedRequest(this.getSpotUrl() + 'v3/allOrders', parameters);
742749
}
@@ -2746,6 +2753,9 @@ export default class Binance {
27462753

27472754
parseOrderBook(data): OrderBook {
27482755
const { lastUpdateId, bids, asks } = data;
2756+
if (!bids || !asks) {
2757+
return data;
2758+
}
27492759
const orderBook: OrderBook = {
27502760
lastUpdateId,
27512761
bids: bids.map(b => zip(['price', 'quantity'], b)),
@@ -3394,7 +3404,7 @@ export default class Binance {
33943404
}
33953405

33963406
/**
3397-
* Get trades for a given symbol
3407+
* Get private trades for a given symbol
33983408
* @see https://developers.binance.com/docs/binance-spot-api-docs/testnet/rest-api/account-endpoints#account-trade-list-user_data
33993409
* @param {string} symbol - the symbol
34003410
* @param {object} options - additional options
@@ -3405,6 +3415,19 @@ export default class Binance {
34053415
return await this.signedRequest(this.getSpotUrl() + 'v3/myTrades', parameters);
34063416
}
34073417

3418+
/**
3419+
* Get private trades for a given symbol
3420+
* @see https://developers.binance.com/docs/binance-spot-api-docs/testnet/rest-api/account-endpoints#account-trade-list-user_data
3421+
* @param {string} symbol - the symbol
3422+
* @param {object} options - additional options
3423+
* @return {promise or undefined} - omitting the callback returns a promise
3424+
*/
3425+
async myTrades(symbol: string, params: Dict = {}): Promise<MyTrade[]> {
3426+
const parameters = this.extend({ symbol: symbol }, params);
3427+
return await this.signedRequest(this.getSpotUrl() + 'v3/myTrades', parameters);
3428+
}
3429+
3430+
34083431
/**
34093432
* Tell api to use the server time to offset time indexes
34103433
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints#check-server-time
@@ -4076,26 +4099,26 @@ export default class Binance {
40764099
return await this.futuresRequest('v1/openInterest', { symbol }, { base: this.getDapiUrl() }).then(r => r.openInterest);
40774100
}
40784101

4079-
async deliveryCandles(symbol: string, interval = "30m", params: Dict = {}): Promise<Candle[]> {
4102+
async deliveryCandles(symbol: string, interval: Interval = "30m", params: Dict = {}): Promise<Candle[]> {
40804103
params.symbol = symbol;
40814104
params.interval = interval;
40824105
return await this.futuresRequest('v1/klines', params, { base: this.getDapiUrl() });
40834106
}
40844107

4085-
async deliveryContinuousKlines(pair: string, contractType = "CURRENT_QUARTER", interval = "30m", params: Dict = {}) {
4108+
async deliveryContinuousKlines(pair: string, contractType = "CURRENT_QUARTER", interval: Interval = "30m", params: Dict = {}) {
40864109
params.pair = pair;
40874110
params.interval = interval;
40884111
params.contractType = contractType;
40894112
return await this.futuresRequest('v1/continuousKlines', params, { base: this.getDapiUrl() });
40904113
}
40914114

4092-
async deliveryIndexKlines(pair: string, interval = "30m", params: Dict = {}) {
4115+
async deliveryIndexKlines(pair: string, interval: Interval = "30m", params: Dict = {}) {
40934116
params.pair = pair;
40944117
params.interval = interval;
40954118
return await this.futuresRequest('v1/indexPriceKlines', params, { base: this.getDapiUrl() });
40964119
}
40974120

4098-
async deliveryMarkPriceKlines(symbol: string, interval = "30m", params: Dict = {}) {
4121+
async deliveryMarkPriceKlines(symbol: string, interval: Interval = "30m", params: Dict = {}) {
40994122
params.symbol = symbol;
41004123
params.interval = interval;
41014124
return await this.futuresRequest('v1/markPriceKlines', params, { base: this.getDapiUrl() });
@@ -4278,6 +4301,7 @@ export default class Binance {
42784301

42794302
/**
42804303
* Creates an order
4304+
* @see https://developers.binance.com/docs/margin_trading/trade/Margin-Account-New-Order
42814305
* @param {string} side - BUY or SELL
42824306
* @param {string} symbol - the symbol to buy
42834307
* @param {numeric} quantity - the quantity required
@@ -4747,7 +4771,7 @@ export default class Binance {
47474771
}
47484772

47494773
let handleFuturesKlineStream = kline => {
4750-
let symbol = kline.s, interval = kline.k.i;
4774+
let symbol = kline.s, interval: Interval = kline.k.i;
47514775
if (!this.futuresMeta[symbol][interval].timestamp) {
47524776
if (typeof (this.futuresKlineQueue[symbol][interval]) !== 'undefined' && kline !== null) {
47534777
this.futuresKlineQueue[symbol][interval].push(kline);
@@ -4974,7 +4998,7 @@ export default class Binance {
49744998
}
49754999

49765000
let handleDeliveryKlineStream = kline => {
4977-
let symbol = kline.s, interval = kline.k.i;
5001+
let symbol = kline.s, interval: Interval = kline.k.i;
49785002
if (!this.deliveryMeta[symbol][interval].timestamp) {
49795003
if (typeof (this.deliveryKlineQueue[symbol][interval]) !== 'undefined' && kline !== null) {
49805004
this.deliveryKlineQueue[symbol][interval].push(kline);
@@ -5467,7 +5491,7 @@ export default class Binance {
54675491
}
54685492

54695493
let handleKlineStreamData = kline => {
5470-
let symbol = kline.s, interval = kline.k.i;
5494+
let symbol = kline.s, interval: Interval = kline.k.i;
54715495
if (!this.info[symbol][interval].timestamp) {
54725496
if (typeof (this.klineQueue[symbol][interval]) !== 'undefined' && kline !== null) {
54735497
this.klineQueue[symbol][interval].push(kline);

src/types.ts

Lines changed: 129 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,8 @@ export type Callback = (...args: any) => any;
124124

125125

126126
export interface IConstructorArgs {
127+
APIKEY: string;
128+
APISECRET: string;
127129
recvWindow: number;
128130
useServerTime: boolean;
129131
reconnect: boolean;
@@ -370,4 +372,130 @@ export interface Ticker {
370372
// _symbol as symbol,
371373
// _callback as callback,
372374
// IConstructorArgs
373-
// }
375+
// }
376+
377+
export type TradingType = 'MARGIN' | 'SPOT'
378+
379+
export interface Account {
380+
accountType: TradingType
381+
balances: AssetBalance[]
382+
buyerCommission: number
383+
canDeposit: boolean
384+
canTrade: boolean
385+
canWithdraw: boolean
386+
makerCommission: number
387+
permissions: TradingType[]
388+
sellerCommission: number
389+
takerCommission: number
390+
updateTime: number
391+
}
392+
393+
export interface AssetBalance {
394+
asset: string
395+
free: string
396+
locked: string
397+
}
398+
399+
400+
export interface FuturesAccountInfo {
401+
feeTier: number
402+
canTrade: boolean
403+
canDeposit: boolean
404+
canWithdraw: boolean
405+
updateTime: number
406+
totalInitialMargin: string
407+
totalMaintMargin: string
408+
totalWalletBalance: string
409+
totalUnrealizedProfit: string
410+
totalMarginBalance: string
411+
totalPositionInitialMargin: string
412+
totalOpenOrderInitialMargin: string
413+
totalCrossWalletBalance: string
414+
totalCrossUnPnl: string
415+
availableBalance: string
416+
maxWithdrawAmount: string
417+
assets: FuturesAsset[]
418+
positions: FuturesAccountPosition[]
419+
}
420+
421+
export interface FuturesAccountPosition {
422+
symbol: string
423+
initialMargin: string
424+
maintMargin: string
425+
unrealizedProfit: string
426+
positionInitialMargin: string
427+
openOrderInitialMargin: string
428+
leverage: string
429+
isolated: boolean
430+
entryPrice: string
431+
maxNotional: string
432+
positionSide: PositionSide
433+
positionAmt: string
434+
notional: string
435+
isolatedWallet: string
436+
updateTime: number
437+
bidNotional: string
438+
askNotional: string
439+
}
440+
441+
442+
export type FuturesAssetType =
443+
| 'DOT'
444+
| 'BTC'
445+
| 'SOL'
446+
| 'BNB'
447+
| 'ETH'
448+
| 'ADA'
449+
| 'USDT'
450+
| 'XRP'
451+
| 'BUSD'
452+
453+
export type FuturesAsset = {
454+
asset: FuturesAssetType
455+
walletBalance: string
456+
unrealizedProfit: string
457+
marginBalance: string
458+
maintMargin: string
459+
initialMargin: string
460+
positionInitialMargin: string
461+
openOrderInitialMargin: string
462+
maxWithdrawAmount: string
463+
crossWalletBalance: string
464+
crossUnPnl: string
465+
availableBalance: string
466+
marginAvailable: boolean
467+
updateTime: number
468+
}
469+
470+
471+
export interface FuturesBalance {
472+
accountAlias: string
473+
asset: string
474+
balance: string
475+
crossWalletBalance: string
476+
crossUnPnl: string
477+
availableBalance: string
478+
maxWithdrawAmount: string
479+
}
480+
481+
482+
export interface QueryOrder {
483+
clientOrderId: string
484+
cummulativeQuoteQty: string
485+
executedQty: string
486+
icebergQty: string
487+
isWorking: boolean
488+
orderId: number
489+
orderListId: number
490+
origQty: string
491+
origQuoteOrderQty: string
492+
price: string
493+
side: OrderSide
494+
status: OrderStatus
495+
stopPrice: string
496+
symbol: string
497+
time: number
498+
timeInForce: TimeInForce
499+
type: OrderType
500+
updateTime: number
501+
}

tests/binance-class-static.test.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ describe( 'Static tests', async function () {
109109
})
110110

111111
it( 'Futures CancelOrder', async function ( ) {
112-
await binance.futuresCancel( 'LTCUSDT', {'orderId': '34234234' })
112+
await binance.futuresCancel( 'LTCUSDT', '34234234')
113113
assert( interceptedUrl.startsWith('https://fapi.binance.com/fapi/v1/order'))
114114
const obj = urlToObject( interceptedUrl.replace('https://fapi.binance.com/fapi/v1/order', '') )
115115
assert.equal( obj.symbol, 'LTCUSDT' )
@@ -141,7 +141,7 @@ describe( 'Static tests', async function () {
141141
})
142142

143143
it( 'LimitBuy', async function ( ) {
144-
await binance.order( 'BUY', 'LTCUSDT', 0.5 )
144+
await binance.order('LIMIT', 'BUY', 'LTCUSDT', 0.5 )
145145
assert.equal( interceptedUrl, 'https://api.binance.com/api/v3/order' )
146146
const obj = urlToObject( interceptedBody )
147147
assert.equal( obj.symbol, 'LTCUSDT' )
@@ -152,7 +152,7 @@ describe( 'Static tests', async function () {
152152
})
153153

154154
it( 'LimitSell', async function ( ) {
155-
await binance.order( 'SELL', 'LTCUSDT', 0.5 )
155+
await binance.order('LIMIT', 'SELL', 'LTCUSDT', 0.5 )
156156
assert.equal( interceptedUrl, 'https://api.binance.com/api/v3/order' )
157157
const obj = urlToObject( interceptedBody )
158158
assert.equal( obj.symbol, 'LTCUSDT' )
@@ -187,7 +187,7 @@ describe( 'Static tests', async function () {
187187
})
188188

189189
it( 'Futures LimitBuy', async function ( ) {
190-
await binance.futuresOrder( 'BUY', 'LTCUSDT', 0.5, 100 )
190+
await binance.futuresOrder('LIMIT', 'BUY', 'LTCUSDT', 0.5, 100 )
191191
assert.isTrue( interceptedUrl.startsWith('https://fapi.binance.com/fapi/v1/order' ))
192192
const obj = urlToObject( interceptedUrl.replace('https://fapi.binance.com/fapi/v1/order?', '') )
193193
assert.equal( obj.symbol, 'LTCUSDT' )
@@ -198,7 +198,7 @@ describe( 'Static tests', async function () {
198198
})
199199

200200
it( 'Futures LimitSell', async function ( ) {
201-
await binance.futuresOrder( 'SELL', 'LTCUSDT', 0.5, 100 )
201+
await binance.futuresOrder('LIMIT', 'SELL', 'LTCUSDT', 0.5, 100 )
202202
assert.isTrue( interceptedUrl.startsWith('https://fapi.binance.com/fapi/v1/order' ))
203203
const obj = urlToObject( interceptedUrl.replace('https://fapi.binance.com/fapi/v1/order?', '') )
204204
assert.equal( obj.symbol, 'LTCUSDT' )

0 commit comments

Comments
 (0)