最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - "AxiosError: Request failed with status code 400" on Market Order Request - Stack Overflow

programmeradmin3浏览0评论

I'm working on a trading bot that connects to Binance Testnet using WebSockets to get ticker updates and Axios to place market orders. However, I'm encountering the following error when trying to place an order:

AxiosError: Request failed with status code 400
    at settle (C:\Users\mansu\OneDrive\Documentos\Node Projects\Binance\node_modules\axios\dist\node\axios.cjs:2026:12)
    at IncomingMessage.handleStreamEnd (C:\Users\mansu\OneDrive\Documentos\Node Projects\Binance\node_modules\axios\dist\node\axios.cjs:3142:11)
    at IncomingMessage.emit (node:events:530:35)
    at endReadableNT (node:internal/streams/readable:1698:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:90:21)

My request to the Binance API looks like this:

const WebSocket = require("ws");
const ws = new WebSocket(`${process.env.STREAM_URL}/${process.env.SYMBOL.toLowerCase()}@ticker`);
const PROFITABILITY = parseFloat(process.env.PROFITABILITY);
let sellPrice = 0;
ws.onmessage = (event) => {
    //console.clear();
    const obj = JSON.parse(event.data);
    console.log("Symbol: "+ obj.s);    
    console.log("Best Ask: "+ obj.a);    

    const currentPrice = parseFloat(obj.a);
    if(sellPrice == 0 && currentPrice < 96100){
        console.log("Bom para comprar");
        newOrder("0.001", "BUY");
        sellPrice = currentPrice * PROFITABILITY;
    }
    else if(sellPrice!== 0 && currentPrice > sellPrice){
        console.log("Bom para vender");
        newOrder("0.001", "SELL");
        sellPrice =0;
    }
    else
        console.log("Esperando...Sell Price: "+ sellPrice);
}
const axios = require('axios');
const crypto = require('crypto');
async function newOrder(quantity, side){
    const data = {
        symbol: process.env.SYMBOL,
        type: 'MARKET',
        side,
        quantity
    };
    const timestamp = Date.now();
    const recvWindow = 10000;
    const signature = crypto
        .createHmac('sha256', process.env.SECRET_KEY)
        .update(`${new URLSearchParams({...data, timestamp, recvWindow})}`)
        .digest('hex');
    const newData = { ...data, timestamp, recvWindow, signature };
    const qs = `?${new URLSearchParams(newData)}`;
    try{
        const result = await axios({
            method: 'POST',
            url: `${process.env.API_URL}/v3/order${qs}`,
            headers: {'X-MBX-APIKEY': process.env.API_KEY }
        })
        console.log(result.data);
    }
    catch(err){
        console.error(err);
    }
}

Environment Variables (.env):

API_URL=/api
API_KEY=MY_API_KEY
SECRET_KEY=MY_SECRET_KEY
STREAM_URL=wss://stream.testnet.binance.vision/ws
SYMBOL=BTCUSDT
PROFITABILITY=1.1

What I've Tried:

Checked API key and secret key – they are correct and have proper permissions.

Checked if quantity is a string or a number – converted it to a string, but the issue persists.

Ensured the signature is properly generated – using HMAC SHA256 with the secret key.

Verified Binance API documentation – I am following the correct parameter structure.

Checked for any spaces in .env values – cleaned and reloaded environment variables.

I'm working on a trading bot that connects to Binance Testnet using WebSockets to get ticker updates and Axios to place market orders. However, I'm encountering the following error when trying to place an order:

AxiosError: Request failed with status code 400
    at settle (C:\Users\mansu\OneDrive\Documentos\Node Projects\Binance\node_modules\axios\dist\node\axios.cjs:2026:12)
    at IncomingMessage.handleStreamEnd (C:\Users\mansu\OneDrive\Documentos\Node Projects\Binance\node_modules\axios\dist\node\axios.cjs:3142:11)
    at IncomingMessage.emit (node:events:530:35)
    at endReadableNT (node:internal/streams/readable:1698:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:90:21)

My request to the Binance API looks like this:

const WebSocket = require("ws");
const ws = new WebSocket(`${process.env.STREAM_URL}/${process.env.SYMBOL.toLowerCase()}@ticker`);
const PROFITABILITY = parseFloat(process.env.PROFITABILITY);
let sellPrice = 0;
ws.onmessage = (event) => {
    //console.clear();
    const obj = JSON.parse(event.data);
    console.log("Symbol: "+ obj.s);    
    console.log("Best Ask: "+ obj.a);    

    const currentPrice = parseFloat(obj.a);
    if(sellPrice == 0 && currentPrice < 96100){
        console.log("Bom para comprar");
        newOrder("0.001", "BUY");
        sellPrice = currentPrice * PROFITABILITY;
    }
    else if(sellPrice!== 0 && currentPrice > sellPrice){
        console.log("Bom para vender");
        newOrder("0.001", "SELL");
        sellPrice =0;
    }
    else
        console.log("Esperando...Sell Price: "+ sellPrice);
}
const axios = require('axios');
const crypto = require('crypto');
async function newOrder(quantity, side){
    const data = {
        symbol: process.env.SYMBOL,
        type: 'MARKET',
        side,
        quantity
    };
    const timestamp = Date.now();
    const recvWindow = 10000;
    const signature = crypto
        .createHmac('sha256', process.env.SECRET_KEY)
        .update(`${new URLSearchParams({...data, timestamp, recvWindow})}`)
        .digest('hex');
    const newData = { ...data, timestamp, recvWindow, signature };
    const qs = `?${new URLSearchParams(newData)}`;
    try{
        const result = await axios({
            method: 'POST',
            url: `${process.env.API_URL}/v3/order${qs}`,
            headers: {'X-MBX-APIKEY': process.env.API_KEY }
        })
        console.log(result.data);
    }
    catch(err){
        console.error(err);
    }
}

Environment Variables (.env):

API_URL=https://testnet.binance.vision/api
API_KEY=MY_API_KEY
SECRET_KEY=MY_SECRET_KEY
STREAM_URL=wss://stream.testnet.binance.vision/ws
SYMBOL=BTCUSDT
PROFITABILITY=1.1

What I've Tried:

Checked API key and secret key – they are correct and have proper permissions.

Checked if quantity is a string or a number – converted it to a string, but the issue persists.

Ensured the signature is properly generated – using HMAC SHA256 with the secret key.

Verified Binance API documentation – I am following the correct parameter structure.

Checked for any spaces in .env values – cleaned and reloaded environment variables.

Share Improve this question asked 3 hours ago reimannsurreimannsur 11 bronze badge 1
  • Since we are unable to reproduce the issue, the only thing I could say is to change update .update(${new URLSearchParams({...data, timestamp, recvWindow})}) to .update(new URLSearchParams({...data, timestamp, recvWindow}).toString()) to see if it works after changing it. – Caden Finkelstein Commented 2 hours ago
Add a comment  | 

1 Answer 1

Reset to default 0

Resolved!

I was facing a "400 Bad Request" error while trying to place market orders using the Binance Testnet API. After double-checking my API keys, request parameters, and signature generation, I finally discovered the issue: the system time on my Windows machine was not accurate.

Binance requires an exact timestamp when sending requests, as it's used for validating the HMAC SHA256 signature. If the system clock is even a few seconds off, the generated signature becomes invalid, leading to a 400 Bad Request error.

ptbtime1.ptb.de

This is one of the Physikalisch-Technische Bundesanstalt (PTB) time servers, known for its high precision.

Thanks!!

发布评论

评论列表(0)

  1. 暂无评论