Skip to content

Commit

Permalink
Merge pull request tiagosiebler#425 from tiagosiebler/resptypefix
Browse files Browse the repository at this point in the history
v2.11.1: fix(tiagosiebler#424) type for newOrderRespType. minor sample fixes.
  • Loading branch information
tiagosiebler authored May 27, 2024
2 parents f74573d + 3f3fa36 commit 934e3ae
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 78 deletions.
70 changes: 34 additions & 36 deletions examples/rest-future-bracket-order.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
import {
USDMClient,
NewFuturesOrderParams
} from '../src/index';
import { USDMClient, NewFuturesOrderParams } from '../src/index';

const key = process.env.APIKEY || 'APIKEY';
const secret = process.env.APISECRET || 'APISECRET';

const client = new USDMClient({
api_key: key,
api_secret: secret,
beautifyResponses: true
beautifyResponses: true,
});

const symbol = 'ETHUSDT';
Expand All @@ -20,54 +17,55 @@ const symbol = 'ETHUSDT';
// TODO: check balance and do other validations

const assetPrices = await client.getMarkPrice({
symbol: "ETHUSDT"
})
const markPrice: number = Number(assetPrices.markPrice)
const stopLossPrice = Number(markPrice * 99.9 / 100).toFixed(2)
const takeProfitPrice = Number(markPrice * 100.1 / 100).toFixed(2)
symbol: 'ETHUSDT',
});
const markPrice: number = Number(assetPrices.markPrice);
const stopLossPrice = Number((markPrice * 99.9) / 100).toFixed(2);
const takeProfitPrice = Number((markPrice * 100.1) / 100).toFixed(2);

// create three orders
// 1. entry order (GTC),
// 2. take profit order (GTE_GTC),
// 3. stop loss order (GTE_GTC)

const entryOrder: NewFuturesOrderParams<string> = {
positionSide: "BOTH",
quantity: "0.01",
reduceOnly: "false",
side: "BUY",
symbol: "ETHUSDT",
type: "MARKET",
positionSide: 'BOTH',
quantity: '0.01',
reduceOnly: 'false',
side: 'BUY',
symbol: 'ETHUSDT',
type: 'MARKET',
};

const takeProfitOrder: NewFuturesOrderParams<string> = {
positionSide: "BOTH",
priceProtect: "TRUE",
quantity: "0.01",
side: "SELL",
positionSide: 'BOTH',
priceProtect: 'TRUE',
quantity: '0.01',
side: 'SELL',
stopPrice: takeProfitPrice,
symbol: "ETHUSDT",
timeInForce: "GTE_GTC",
type: "TAKE_PROFIT_MARKET",
workingType: "MARK_PRICE",
closePosition: "true"
symbol: 'ETHUSDT',
timeInForce: 'GTE_GTC',
type: 'TAKE_PROFIT_MARKET',
workingType: 'MARK_PRICE',
closePosition: 'true',
};

const stopLossOrder: NewFuturesOrderParams<string> = {
positionSide: "BOTH",
priceProtect: "TRUE",
quantity: "0.01",
side: "SELL",
positionSide: 'BOTH',
priceProtect: 'TRUE',
quantity: '0.01',
side: 'SELL',
stopPrice: stopLossPrice,
symbol: "ETHUSDT",
timeInForce: "GTE_GTC",
type: "STOP_MARKET",
workingType: "MARK_PRICE",
closePosition: "true"
symbol: 'ETHUSDT',
timeInForce: 'GTE_GTC',
type: 'STOP_MARKET',
workingType: 'MARK_PRICE',
closePosition: 'true',
};

const openedOrder = await client.submitMultipleOrders([entryOrder, takeProfitOrder, stopLossOrder])
.catch(e => console.log(e?.body || e));
const openedOrder = await client
.submitMultipleOrders([entryOrder, takeProfitOrder, stopLossOrder])
.catch((e) => console.log(e?.body || e));
console.log(openedOrder);
} catch (e) {
console.log(e);
Expand Down
76 changes: 56 additions & 20 deletions examples/rest-spot-private-trade.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { NewSpotOrderParams, OrderResponseFull, MainClient, SymbolPrice } from '../src/index';
import {
NewSpotOrderParams,
OrderResponseFull,
MainClient,
SymbolPrice,
} from '../src/index';

// or
// import { MainClient } from 'binance';
Expand All @@ -12,9 +17,9 @@ const client = new MainClient({
beautifyResponses: true,
});

const entryAmountPercent = 50;// trigger trade with 50%
const entryAmountPercent = 50; // trigger trade with 50%
const symbol = 'BTCUSDT';
const assetDecimalPlaces = 4;// get this from exchange info, it varies per asset
const assetDecimalPlaces = 4; // get this from exchange info, it varies per asset

// method to trim down to decimal.
function trimToDecimalPlaces(number: number, precision: number): number {
Expand All @@ -36,7 +41,7 @@ function trimToDecimalPlaces(number: number, precision: number): number {
*/
const balance = await client.getBalances();

const usdtBal = balance.find(assetBal => assetBal.coin === 'USDT');
const usdtBal = balance.find((assetBal) => assetBal.coin === 'USDT');
// console.log('USDT balance object: ', usdtBal);

const usdtAvailable = usdtBal?.free;
Expand All @@ -46,12 +51,16 @@ function trimToDecimalPlaces(number: number, precision: number): number {
}

const buyAmountValue = Number(usdtAvailable) * (50 / 100);
console.log(`Executing trade with ${entryAmountPercent}% of ${usdtAvailable} USDT = ${buyAmountValue} USDT value`);
console.log(
`Executing trade with ${entryAmountPercent}% of ${usdtAvailable} USDT = ${buyAmountValue} USDT value`,
);

/**
* Get last asset price
*/
const btcTicker = await client.getSymbolPriceTicker({ symbol: symbol }) as SymbolPrice;
const btcTicker = (await client.getSymbolPriceTicker({
symbol: symbol,
})) as SymbolPrice;
const lastPrice = btcTicker?.price;
if (!lastPrice) {
return console.error('Error: no price returned');
Expand All @@ -60,8 +69,12 @@ function trimToDecimalPlaces(number: number, precision: number): number {
/**
* Calculate and submit buy amount
*/
const buyAmountBtc = +(buyAmountValue / Number(lastPrice)).toFixed(assetDecimalPlaces);
console.log(`Last ${symbol} price: ${lastPrice} => will buy ${buyAmountBtc} ${symbol}`);
const buyAmountBtc = +(buyAmountValue / Number(lastPrice)).toFixed(
assetDecimalPlaces,
);
console.log(
`Last ${symbol} price: ${lastPrice} => will buy ${buyAmountBtc} ${symbol}`,
);

const buyOrderRequest: NewSpotOrderParams = {
symbol: symbol,
Expand All @@ -73,39 +86,62 @@ function trimToDecimalPlaces(number: number, precision: number): number {
* RESULT = fill state -> OrderResponseResult
* FULL = fill state + detail on fills and other detail -> OrderResponseFull
*/
newOrderRespType: 'FULL'
newOrderRespType: 'FULL',
};

console.log(`Submitting buy order: `, buyOrderRequest)
console.log(`Submitting buy order: `, buyOrderRequest);
await client.testNewOrder(buyOrderRequest);
const buyOrderResult = await client.submitNewOrder(buyOrderRequest) as OrderResponseFull;
console.log(`Order result: `, JSON.stringify({ request: buyOrderRequest, response: buyOrderResult }, null, 2));
const buyOrderResult = (await client.submitNewOrder(
buyOrderRequest,
)) as OrderResponseFull;
console.log(
`Order result: `,
JSON.stringify(
{ request: buyOrderRequest, response: buyOrderResult },
null,
2,
),
);

/**
* Process bought fills and submit sell amount
*/
const assetAmountBought = buyOrderResult.executedQty;
const assetFillsMinusFees = buyOrderResult.fills.reduce(
(sum, fill) => sum + Number(fill.qty) - (fill.commissionAsset !== 'BNB' ? Number(fill.commission) : 0), 0
(sum, fill) =>
sum +
Number(fill.qty) -
(fill.commissionAsset !== 'BNB' ? Number(fill.commission) : 0),
0,
);
console.log(
`Filled buy ${symbol} ${assetAmountBought} : bought minus fees ${assetFillsMinusFees}`,
);
console.log(`Filled buy ${symbol} ${assetAmountBought} : bought minus fees ${assetFillsMinusFees}`);

const sellOrderRequest: NewSpotOrderParams = {
symbol: symbol,
quantity: trimToDecimalPlaces(assetFillsMinusFees, assetDecimalPlaces),
side: 'SELL',
type: 'MARKET',
newOrderRespType: 'FULL'
newOrderRespType: 'FULL',
};

console.log(`Submitting sell order: `, sellOrderRequest)
console.log(`Submitting sell order: `, sellOrderRequest);
await client.testNewOrder(sellOrderRequest);
const sellOrderResult = await client.submitNewOrder(sellOrderRequest) as OrderResponseFull;
console.log(`Order result: `, JSON.stringify({ request: sellOrderRequest, response: sellOrderResult }, null, 2));
const sellOrderResult = (await client.submitNewOrder(
sellOrderRequest,
)) as OrderResponseFull;

console.log(
`Order result: `,
JSON.stringify(
{ request: sellOrderRequest, response: sellOrderResult },
null,
2,
),
);

console.log(`All ${symbol} should have been sold!`);


} catch (e) {
console.error('Error: request failed: ', e);
}
Expand Down
1 change: 1 addition & 0 deletions examples/rest-usdm-order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ async function start() {
symbol: 'BTCUSDT',
type: 'MARKET',
quantity: 0.001,
// newOrderRespType: 'FULL',
});

console.log('market sell result: ', result);
Expand Down
16 changes: 8 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "binance",
"version": "2.11.0",
"version": "2.11.1",
"description": "Node.js & JavaScript SDK for Binance REST APIs & WebSockets, with TypeScript & end-to-end tests.",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
6 changes: 3 additions & 3 deletions src/types/spot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ export interface ExchangeInfoParams {

export interface NewSpotOrderParams<
T extends OrderType = OrderType,
RT extends OrderResponseType | undefined = undefined,
RT extends OrderResponseType | undefined = OrderResponseType,
> {
symbol: string;
side: OrderSide;
Expand All @@ -435,7 +435,7 @@ export type CancelReplaceMode = 'STOP_ON_FAILURE' | 'ALLOW_FAILURE';

export interface ReplaceSpotOrderParams<
T extends OrderType = OrderType,
RT extends OrderResponseType | undefined = undefined,
RT extends OrderResponseType | undefined = OrderResponseType,
> extends NewSpotOrderParams<T, RT> {
cancelReplaceMode: CancelReplaceMode;
cancelNewClientOrderId?: string;
Expand Down Expand Up @@ -814,7 +814,7 @@ export interface ReplaceSpotOrderResultError {

export interface ReplaceSpotOrderResultSuccess<
T extends OrderType = OrderType,
RT extends OrderResponseType | undefined = undefined,
RT extends OrderResponseType | undefined = OrderResponseType,
> extends GenericReplaceSpotOrderResult<
CancelSpotOrderResult,
OrderResponseTypeFor<RT, T>
Expand Down
21 changes: 11 additions & 10 deletions src/usdm-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ export class USDMClient extends BaseRestClient {
return this.get('fapi/v1/aggTrades', params);
}

getMarkPrice(params: BasicSymbolParam): Promise<MarkPrice>;
getMarkPrice(): Promise<MarkPrice[]>;

/**
* Index Price and Mark Price
*/
Expand Down Expand Up @@ -272,22 +275,20 @@ export class USDMClient extends BaseRestClient {
return this.getPrivate('fapi/v1/multiAssetsMargin');
}

submitNewOrder(
params: NewFuturesOrderParams,
): Promise<NewOrderResult> {
submitNewOrder(params: NewFuturesOrderParams): Promise<NewOrderResult> {
this.validateOrderId(params, 'newClientOrderId');
return this.postPrivate('fapi/v1/order', params);
}

/**
/**
* Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue
*/
modifyOrder(
params: ModifyFuturesOrderParams,
): Promise<ModifyFuturesOrderResult> {
return this.putPrivate('fapi/v1/order', params);
}
modifyOrder(
params: ModifyFuturesOrderParams,
): Promise<ModifyFuturesOrderResult> {
return this.putPrivate('fapi/v1/order', params);
}

/**
* Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected.
*
Expand Down
5 changes: 5 additions & 0 deletions tea.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
version: 1.0.0
codeOwners:
- '0xeb1a7BF44a801e33a339705A266Afc0Cba3D6D54'
quorum: 1

0 comments on commit 934e3ae

Please sign in to comment.