1.0.7 • Published 2 years ago
binance_sa v1.0.7
Binance Websocket and Api
Use
const binance = require("binance_sa")({ apiKey: '', apiSecret: '' });
server time
// get time server binance
let {serverTime} = await binance.serverTime();
console.log("st", serverTime);
orderbook
websockt
// get order book with websocket and use object orderbook
let orderbook = await binance.orderbook({
pair: 'ethusdt',
type: 'futures', // optional spot:empty, futures:futures
});
console.log(orderbook.getOrderbook());
console.log(orderbook.getSymbol());
console.log(orderbook.getBestBid());
console.log(orderbook.getBestAsk());
console.log(orderbook.justInitialized());
await binance.tools.sleep(5000);
console.log(orderbook.getOrderbook());
console.log(orderbook.inspect());
kline
websocket
// get order book with websocket and use object orderbook
let kline = await binance.kline({symbol: "BTCUSDT", interval: "1h"});
/*
m -> minutes; h -> hours; d -> days; w -> weeks; M -> months
1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M
*/
kline.getKline()
kline.getsymbol()
kline.getInterval()
kline.inspect()
api
let kline = await binance.klineSnapshot({SYMBOL: "bnbbtc", interval: "1m"});
24hr status
let trade24hr = await binance.tiker24hr("bnbusdt");
market
websocket
// get websocket market
let marketModel = await binance.market();
console.log("marketModel", marketModel.getMarket());
pair
websocket
// get websocket pair data
var a = await binance.pair('ethusdt');
console.log('a', a.getCoin());
await binance.tools.sleep(5000)
console.log('a', a.getCoin());
private apikey apisecret
get account info
var accountInfo = await binance.accountInfo(apiKey, apiSecret); // contain permisions and balances account
get asset
var assets = await binance.getAsset(apiKey, apiSecret); // get all asset
check permission
var permission = await binance.checkPermission(apiKey, apiSecret); // get permisions
order
SPOT :
add new order
var a = await binance.newOrder(apiKey, apiSecret, {
recvWindow: 60000,
symbol: 'BTCUSDT',
side: 'SELL', // SELL or BUY
type: "MARKET", //LIMIT or MARKET or STOP or STOP_LOSS_LIMIT
// timeInForce: 'GTC',
// quantity,
// price,
// newClientOrderId,
// stopPrice,
// quoteOrderQty: 50
});
Some additional mandatory parameters based on order type:
Type | Additional mandatory parameters | Additional Information
LIMIT timeInForce, quantity, price
MARKET quantity or quoteOrderQty MARKET orders using the quantity field specifies the amount of the base asset the user wants to buy or sell at the market price.
E.g. MARKET order on BTCUSDT will specify how much BTC the user is buying or selling.
MARKET orders using quoteOrderQty specifies the amount the user wants to spend (when buying) or receive (when selling) the quote asset; the correct quantity will be determined based on the market liquidity and quoteOrderQty.
E.g. Using the symbol BTCUSDT:
BUY side, the order will buy as many BTC as quoteOrderQty USDT can.
SELL side, the order will sell as much BTC needed to receive quoteOrderQty USDT.
STOP_LOSS quantity, stopPrice This will execute a MARKET order when the stopPrice is reached.
STOP_LOSS_LIMIT timeInForce, quantity, price, stopPrice
TAKE_PROFIT quantity, stopPrice This will execute a MARKET order when the stopPrice is reached.
TAKE_PROFIT_LIMIT timeInForce, quantity, price, stopPrice
LIMIT_MAKER quantity, price This is a LIMIT order that will be rejected if the order immediately matches and trades as a taker.
This is also known as a POST-ONLY order.
Other info:
Any LIMIT or LIMIT_MAKER type order can be made an iceberg order by sending an icebergQty.
Any order with an icebergQty MUST have timeInForce set to GTC.
MARKET orders using quoteOrderQty will not break LOT_SIZE filter rules; the order will execute a quantity that will have the notional value as close as possible to quoteOrderQty. Trigger order price rules against market price for both MARKET and LIMIT versions:
Price above market price: STOP_LOSS BUY, TAKE_PROFIT SELL
Price below market price: STOP_LOSS SELL, TAKE_PROFIT BUY
check order status
var a = await binance.checkOrder(apiKey, apiSecret, {
// recvWindow: 60000,
symbol: 'BTCUSDT',
orderId: 1,
// origClientOrderId: 1,
// cummulativeQuoteQty: "0.0",
});
console.log("aa", a);
Notes:
Either 'orderId' or 'origClientOrderId' must be sent.
For some historical orders 'cummulativeQuoteQty' will be < 0, meaning the data is not available at this time.
delete order
var a = await binance.deleteOrder(apiKey, apiSecret, {
// recvWindow: 60000,
symbol: 'BTCUSDT',
orderId: 1,
// origClientOrderId:1,
});
console.log("aa", a);
get open orders
var a = await binance.openOrders(apiKey, apiSecret, {
symbol: 'BTCUSDT',
});
console.log("data", a);
// If the symbol is not sent, orders for all symbols will be returned in an array.
get all orders
var a = await binance.allOrders(apiKey, apiSecret, {
symbol: 'BTCUSDT',
});
console.log("aa", a)
//Get all account orders; active, canceled, or filled.
// Parameters:
//
// Name Type Mandatory Description
// symbol STRING YES
// orderId LONG NO
// startTime LONG NO
// endTime LONG NO
// limit INT NO Default 500; max 1000.
// recvWindow LONG NO The value cannot be greater than 60000
// timestamp LONG YES
Notes:
If `orderId` is set, it will get "orders" >= that "orderId". Otherwise most recent orders are returned.
For some historical orders "cummulativeQuoteQty" will be < 0, meaning the data is not available at this time.
If "startTime" and/or "endTime" provided, "orderId" is not required.
FUTURES:
order
let newOrder = await binance.futuresOrder({
symbol: 'BTCUSDT',
side: 'BUY',
type: 'MARKET',
quantity: 1,
positionSide: 'LONG',
})
Name Type Mandatory Description
symbol STRING YES
side ENUM YES
positionSide ENUM NO Default BOTH for One-way Mode ; LONG or SHORT for Hedge Mode. It must be sent in Hedge Mode.
type ENUM YES
timeInForce ENUM NO
quantity DECIMAL NO Cannot be sent with closePosition=true(Close-All)
reduceOnly STRING NO "true" or "false". default "false". Cannot be sent in Hedge Mode; cannot be sent with closePosition=true
price DECIMAL NO
newClientOrderId STRING NO A unique id among open orders. Automatically generated if not sent. Can only be string following the rule: ^[\.A-Z\:/a-z0-9_-]{1,36}$
stopPrice DECIMAL NO Used with STOP/STOP_MARKET or TAKE_PROFIT/TAKE_PROFIT_MARKET orders.
closePosition STRING NO true, false;Close-All,used with STOP_MARKET or TAKE_PROFIT_MARKET.
activationPrice DECIMAL NO Used with TRAILING_STOP_MARKET orders, default as the latest price(supporting different workingType)
callbackRate DECIMAL NO Used with TRAILING_STOP_MARKET orders, min 0.1, max 5 where 1 for 1%
workingType ENUM NO stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE". Default "CONTRACT_PRICE"
priceProtect STRING NO "TRUE" or "FALSE", default "FALSE". Used with STOP/STOP_MARKET or TAKE_PROFIT/TAKE_PROFIT_MARKET orders.
newOrderRespType ENUM NO "ACK", "RESULT", default "ACK"
recvWindow LONG NO
Order with type STOP, parameter timeInForce can be sent ( default GTC).
Order with type TAKE_PROFIT, parameter timeInForce can be sent ( default GTC).
Condition orders will be triggered when:
If parameterpriceProtectis sent as true:
when price reaches the stopPrice ,the difference rate between "MARK_PRICE" and "CONTRACT_PRICE" cannot be larger than the "triggerProtect" of the symbol
"triggerProtect" of a symbol can be got from GET /fapi/v1/exchangeInfo
STOP, STOP_MARKET:
BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= stopPrice
SELL: latest price ("MARK_PRICE" or "CONTRACT_PRICE") <= stopPrice
TAKE_PROFIT, TAKE_PROFIT_MARKET:
BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") <= stopPrice
SELL: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= stopPrice
TRAILING_STOP_MARKET:
BUY: the lowest price after order placed <= activationPrice, and the latest price >= the lowest price * (1 + callbackRate)
SELL: the highest price after order placed >= activationPrice, and the latest price <= the highest price * (1 - callbackRate)
For TRAILING_STOP_MARKET, if you got such error code.
{"code": -2021, "msg": "Order would immediately trigger."}
means that the parameters you send do not meet the following requirements:
BUY: activationPrice should be smaller than latest price.
SELL: activationPrice should be larger than latest price.
If newOrderRespType is sent as RESULT :
MARKET order: the final FILLED result of the order will be return directly.
LIMIT order with special timeInForce: the final status result of the order(FILLED or EXPIRED) will be returned directly.
STOP_MARKET, TAKE_PROFIT_MARKET with closePosition=true:
Follow the same rules for condition orders.
If triggered,close all current long position( if SELL) or current short position( if BUY).
Cannot be used with quantity paremeter
Cannot be used with reduceOnly parameter
In Hedge Mode,cannot be used with BUY orders in LONG position side. and cannot be used with SELL orders in SHORT position side
batchOrders
let batchOrders = await binance.batchOrders({
batchOrders: 'BTCUSDT',
})
Paremeter rules are same with New Order
Batch orders are processed concurrently, and the order of matching is not guaranteed.
The order of returned contents for batch orders is the same as the order of the order list.
getOrders
let batchOrders = await binance.getFuturesOrder({
symbol: 'BTCUSDT',
})
deleteFuturesOrder
let deleteOrders = await binance.deleteFuturesOrder({
symbol: 'BTCUSDT',
})
deleteAllFuturesOpenOrder
let deleteOrders = await binance.deleteAllFuturesOpenOrder({
symbol: 'BTCUSDT',
})
getAllFuturesOpenOrder
let deleteOrders = await binance.getAllFuturesOpenOrder()
allFuturesOrders
let allFuturesOrders = await binance.allFuturesOrders({
symbol: 'btcusdt'
})
Get all account orders; active, canceled, or filled.
These orders will not be found:
order status is CANCELED or EXPIRED, AND
order has NO filled trade, AND
created time + 7 days < current time
FuturesBalance
let FuturesBalance = await binance.FuturesBalance()
leverage
let leverage = await binance.leverage({
symbol: 'btcusdt'
})
nobitex
orderbook
await orderbookNobitex('BTCUSDT')
add order
let a = await binance.addOrderNobitex({
type: 'buy',
execution: 'market',
srcCurrency: 'usdt',
dstCurrency: 'eth',
amount: 0.0623,
price: 121000,
stopPrice: 118000
});
console.log('a', a)
check status order
console.log(await binance.checkOrderNobitex({
id: 5634,
}))
نکات تکمیلی مشاهده وضعیت سفارش
change status order
console.log(await binance.changeOrderNobitex({
order: 4561,
status: 'canceled'
}))
توضیحات نحوه کنسل و فعال کردن یک سفارش + نوع پارامتر های ورودی
How to setup
npm install
# run test
npm run test
License
صلوات بفرست