jaggedsoft / node-binance-api

Node Binance API is an asynchronous node.js library for the Binance API designed to be easy to use.
MIT License
1.58k stars 768 forks source link

Market Buy Error -1013 #690

Open ffbboy30 opened 3 years ago

ffbboy30 commented 3 years ago

Hi, Im trying to use the MarketBuy function like this let BuyInfo = await binance.marketBuy('TROYBTC', 41666666,'MARKET',(error, ticker) => { if ( error ) console.error(error); console.info("Market Buy response", ticker); console.info("order id: " + ticker.orderId); });

The proxy request options looks like this { symbol: "TROYBTC", side: "BUY", type: "LIMIT", quantity: 43478260, price: 0, timeInForce: "GTC", timestamp: 1624337713439, recvWindow: 5000, signature: "111111111111111111111", }

In return I've this error `'{"code":-1013,"msg":"Invalid price."}',

'content-type': 'application/json;charset=UTF-8',
'content-length': '37',
connection: 'keep-alive',
date: 'Mon, 21 Jun 2021 04:41:57 GMT',
server: 'nginx',
'x-mbx-uuid': 'cdf0a88e-efd8-43ed-81a7-16f36eed05ce',
'x-mbx-used-weight': '1',
'x-mbx-used-weight-1m': '1',
'strict-transport-security': 'max-age=31536000; includeSubdomains',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '1; mode=block',
'x-content-type-options': 'nosniff',
'content-security-policy': "default-src 'self'",
'x-content-security-policy': "default-src 'self'",
'x-webkit-csp': "default-src 'self'",
'cache-control': 'no-cache, no-store, must-revalidate',
pragma: 'no-cache',
expires: '0',
'x-cache': 'Error from cloudfront',
via: '1.1 f59bca6f088aed7c4e862f051be29532.cloudfront.net (CloudFront)',
'x-amz-cf-pop': 'SYD1-C1',
'x-amz-cf-id': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'

},

}` The price is 0 because it is a market buy , I don't understand the error. I've verified the 'test' option and it is set to false. My balance is not null.

Thanks for your help.

ffbboy30 commented 3 years ago

In the request the Order is 'LIMITS' instead 'MARKET', it is replaced because in the code somewhere there is aninitialisation with let opt = { symbol: symbol, side: side, type: 'LIMIT', quantity: quantity };

And after the type is not redifined and it is 'LIMIT' in the webrequest. Thanks

codetinker commented 3 years ago

I also been struggling to open order buy or buy limit. After few hours of googling and trying I finally understood how open order.

If you check on this page, you will get general idea on how to code: https://github.com/jaggedsoft/node-binance-api/blob/master/examples/advanced.md#clamp-order-quantities-to-required-amounts-via-minqty-minnotional-stepsize-when-placing-orders

I'm using XRPUSDT as example:

let 
pair = "XRPUSDT",
priceLimit = 0.5,
lotSize = 1.5, 
currPrice = 0.5905,
infoXRPUSDT = { 
  "status": "TRADING", 
  "minPrice": "0.00010000", 
  "maxPrice": "10000.00000000", 
  "tickSize": "0.00010000", 
  "stepSize": "0.01000000", 
  "minQty": "0.01000000", 
  "maxQty": "9222449.00000000", 
  "minNotional": "10.00000000", 
  "baseAssetPrecision": 8, 
  "quoteAssetPrecision": 8, 
  "orderTypes": ["LIMIT", "LIMIT_MAKER", "MARKET", "STOP_LOSS_LIMIT", "TAKE_PROFIT_LIMIT"], 
  "icebergAllowed": true 
}

binance.prices(function (err, ticker) {
  if (lotSize < 1.1) lotSize = 1.1;

  if (err) {
    err = JSON.parse(err.body);
    console.log('Error #' + err.code + ': ' + err.msg);
  } else {
    let currPrice = ticker[pair];
    binance.balance(function (err, balances) {
      if (typeof balances.USDT !== 'undefined') {
        let currBalance = balances.USDT.available,
          minNotional = Number(infoXRPUSDT.minNotional),
          stepSize = cfg[pair].stepSize,
          tmp1 = stepSize.split('.'),
          tmp2 = tmp1[1].split(''),
          minQuantity = minNotional / currPrice,
          minBalance = minQuantity * currPrice,
          quantity = (minBalance * lotSize) / priceLimit ;

        if (minBalance * lotSize > currBalance) quantity = minBalance / priceLimit ;

        // This will fix "Error #-1013: Invalid price". because of price step
        if (tmp1[0].indexOf('1') >= 0) quantity = parseFloat(quantity).toFixed(0);
          else {
          let nPrecision = 1;
          for (let x of tmp2) {
            if (x == '1') break;
            nPrecision++;
          }
          quantity = parseFloat(quantity).toFixed(nPrecision);
        }

        // format precision, else it will throw error code 1xxx.
        quantity = parseFloat(quantity).toFixed(cfg[pair].baseAssetPrecision);

        if (minBalance > currBalance) {
          console.log('Current balance USDT ' + currBalance + '. Minimum balance USDT ' + minBalance + ' require.');
        } else {
          binance.buy(pair, quantity, priceLimit , { type: 'LIMIT' }, (err, response) => {
            if (err) {
              err = JSON.parse(err.body);
             console.log('Error #' + err.code + ': ' + err.msg);
            } else {
              console.info('Limit Buy response', response);
              console.info('statusCode', response.statusCode);
              console.info('statusMessage', response.statusMessage);
              console.info('order id: ' + response.orderId);
            }
          });
        }
      } else if (err) {
        err = JSON.parse(err.body);
        console.log('Error checking account balance USDT: (' + err.code + ')' + err.msg);
      } else {
        console.log('Error checking account balance USDT: Unknown error.');
      }
    });
  }
});

As for order type 'MARKET', just replace with below code. Tested works.

binance.marketBuy(pair, quantity, (err, response) => {

Hope this help =)

ffbboy30 commented 3 years ago

Thanks for the tips. I don't understand where you find lotSize = 1.5,

I just want to calculate the coin quantity according my available balance

I've tried for TROY

balance : 0.00000080 Ticker price 0.00000020

So Qty is logically : 3

But I've a big error '{"code":-1013,"msg":"Filter failure: MIN_NOTIONAL"}', with this coin characteristics status: "TRADING", minPrice: "0.00000001", maxPrice: "1000.00000000", tickSize: "0.00000001", stepSize: "1.00000000", minQty: "1.00000000", maxQty: "92141578.00000000", minNotional: "0.00010000", orderTypes: [ "LIMIT", "LIMIT_MAKER", "MARKET", "STOP_LOSS_LIMIT", "TAKE_PROFIT_LIMIT", ], icebergAllowed: true,

codetinker commented 3 years ago

lotSize is what i use to multiple the order. I'm quite new with btc or binance. About a week or two. From what I know, min to open order is usually USDT10.1 Entering USDT10 (minNotional) usually will failed, using the app or web.

so I added lotSize and multiple the min amount of USDT. (lotSize * minNotional) For me, i kinda like this approach. I don't know if the is another way.

codetinker commented 3 years ago

if you using my code above, you wont get error. But you need to get the info for TROY first:

binance.exchangeInfo(function(error, data) {

check the link above

"Filter failure: MIN_NOTIONAL" this mean quantity need to be in the correct format. (precision and price step)

ffbboy30 commented 3 years ago

Cool it works now I need to code the sell limit