You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

node-binance-api报错TypeError: callback.call is not a function求助

问题:基于node-binance-api的量化交易Bot报错:TypeError: callback.call is not a function 及 Cannot read properties of undefined (reading 'map')

运行基于node-binance-api开发的量化交易Bot时,反复出现两个错误:TypeError: callback.call is not a function 和 Cannot read properties of undefined (reading 'map')。已执行npm update更新依赖,尝试多种方法仍未解决。以下是相关配置、代码及完整报错输出:

config.json

{
  "exchangeSettings": {
    "name": "Binance",
    "api": {
      "apiKey": "********************",
      "secret": "********************"
    },
    "testMode": true
  },
  "strategy": {
    "shortSMA": 7,
    "longSMA": 25,
    "interval": 3600000,
    "tradeSymbol": "BNBUSDT",
    "tradeQuantity": 0.1,
    "maxTradeQuantity": 1,
    "stopLossPercentage": 5,
    "takeProfitPercentage": 10,
    "maxDrawdownPercentage": 20,
    "riskRewardRatio": 2
  },
  "notificationSettings": {
    "enableEmail": true,
    "email": "*******@yahoo.com",
    "smtpSettings": {
      "host": "smtp.mail.yahoo.com",
      "port": 465,
      "username": "*******@yahoo.com",
      "password": "**********",
      "secure": true
    }
  },
  "logging": {
    "logLevel": "INFO",
    "logToFile": true,
    "filePath": "/Users/olugbengaoyeneye/GinBot/log"
  }
}

Bot.js

// bot.js

// 导入必要库
const fs = require('fs');
const Binance = require('node-binance-api');

// 加载配置
const configPath = './config.json';
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));

// 初始化Binance Bot
const binance = new Binance().options({
  APIKEY: config.exchangeSettings.api.apiKey,
  APISECRET: config.exchangeSettings.api.secret,
  useServerTime: true,
  test: config.exchangeSettings.testMode // 测试模式设为true
});

// 计算简单移动平均线(SMA)
function calculateSMA(data, period) {
    let sum = 0;
    for (let i = 0; i < period; i++) {
        sum += parseFloat(data[i]);
    }
    return sum / period;
}

// 获取并显示账户余额
const displayBalance = async () => {
  try {
    const balanceData = await binance.balance();
    console.log("账户余额:", balanceData);
  } catch (error) {
    console.error("获取余额失败:", error);
  }
};

// 执行交易策略
const executeStrategy = async () => {
  try {
    console.log("执行交易策略...");

    // 获取历史K线数据
    let candles = await binance.candlesticks(config.strategy.tradeSymbol, '1h', {limit: 50});
    let closingPrices = candles.map(candle => candle[4]); // 第4位是收盘价

    // 计算短期和长期SMA
    let shortSMA = calculateSMA(closingPrices, config.strategy.shortSMA);
    let longSMA = calculateSMA(closingPrices, config.strategy.longSMA);

    console.log(`短期SMA: ${shortSMA}, 长期SMA: ${longSMA}`);

    // SMA交叉策略逻辑
    if (shortSMA > longSMA) {
        console.log("短期SMA高于长期SMA,考虑买入。");
        // 此处添加买入逻辑
    } else if (shortSMA < longSMA) {
        console.log("短期SMA低于长期SMA,考虑卖出。");
        // 此处添加卖出逻辑
    } else {
        console.log("无明确趋势,持有。");
    }

    // 添加更多交易逻辑
  } catch (error) {
    console.error("执行策略出错:", error);
  }
};

// 启动交易Bot
const startTradingBot = () => {
  console.log("启动交易Bot...");

  // 显示账户余额
  displayBalance();

  // 按配置的间隔执行策略
  setInterval(executeStrategy, config.strategy.interval);
};

// 启动Bot
startTradingBot();

报错输出

olugbengaoyeneye@Olugbengas-MBP GinBot % node bot.js           
启动交易Bot...
(node:37772) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
账户余额: {
  BTC: { available: '0.00000000', onOrder: '0.00000000' },
  LTC: { available: '0.00000000', onOrder: '0.00000000' },
  ETH: { available: '0.00003672', onOrder: '0.00000000' },

. . .


  MEME: { available: '0.00000000', onOrder: '0.00000000' },
  TIA: { available: '0.00000000', onOrder: '0.00000000' }
}

执行交易策略...
Error executing strategy: TypeError: Cannot read properties of undefined (reading 'map')
    at Timeout.executeStrategy [as _onTimeout] (/Users/olugbengaoyeneye/GinBot/bot.js:45:33)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
/Users/olugbengaoyeneye/GinBot/node_modules/node-binance-api/node-binance-api.js:3847
                    return callback.call( this, error, data, symbol );
                                    ^

TypeError: callback.call is not a function
    at /Users/olugbengaoyeneye/GinBot/node_modules/node-binance-api/node-binance-api.js:3847:37
    at Request._callback (/Users/olugbengaoyeneye/GinBot/node_modules/node-binance-api/node-binance-api.js:188:16)
    at self.callback (/Users/olugbengaoyeneye/GinBot/node_modules/request/request.js:185:22)
    at Request.emit (node:events:515:28)
    at Request.<anonymous> (/Users/olugbengaoyeneye/GinBot/node_modules/request/request.js:1154:10)
    at Request.emit (node:events:515:28)
    at IncomingMessage.<anonymous> (/Users/olugbengaoyeneye/GinBot/node_modules/request/request.js:1076:12)
    at Object.onceWrapper (node:events:629:28)
    at IncomingMessage.emit (node:events:527:35)
    at endReadableNT (node:internal/streams/readable:1589:12)

Node.js v21.1.0
olugbengaoyeneye@Olugbengas-MBP GinBot % 
解决方案

1. 修复candlesticks方法调用格式

node-binance-api的candlesticks方法在async/await模式下参数解析存在问题,第三个参数若直接传配置对象会被识别为回调函数,导致callback.call is not a function错误。需调整参数顺序:

// 原错误调用
let candles = await binance.candlesticks(config.strategy.tradeSymbol, '1h', {limit: 50});

// 修改为(添加占位的false参数)
let candles = await binance.candlesticks(config.strategy.tradeSymbol, '1h', false, {limit: 50});

// 或使用回调转Promise的兼容写法
let candles = await new Promise((resolve, reject) => {
  binance.candlesticks(config.strategy.tradeSymbol, '1h', (error, data) => {
    error ? reject(error) : resolve(data);
  }, {limit: 50});
});

2. 增加数据有效性校验

在调用map前检查K线数据是否有效,避免Cannot read properties of undefined (reading 'map')错误:

console.log("执行交易策略...");

// 获取历史K线数据
let candles = await binance.candlesticks(config.strategy.tradeSymbol, '1h', false, {limit: 50});

// 新增数据校验
if (!candles || !Array.isArray(candles)) {
  console.error("K线数据获取失败:数据为空或格式错误");
  return;
}

let closingPrices = candles.map(candle => candle[4]);

3. 解决版本兼容性问题

  • Node.js v21与旧版node-binance-api存在兼容性问题,建议降级到Node.js 18 LTS版本;
  • 旧版node-binance-api依赖已废弃的request库,可安装最新beta版本替换为axios:
    npm install node-binance-api@beta
    

内容的提问来源于stack exchange,提问作者softgi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 21:10:55