0

我正在使用我使用 Nodejs (Express)、Postgres 和 React 创建的交易机器人。React 仅适用于 UI,所有工作都使用 Node.js 完成。Postgres 用于在数据库中存储交易信息。

该应用程序仅在我的本地主机上运行。

工作流程是这样的:

  1. 获取交易平台上所有加密货币的列表(1 个外部 API 请求)
  2. 循环获取每个加密并对其执行一些“大量”计算(+150 个外部 API 请求并调用大量异步辅助函数)
  3. 如果一种加密货币满足要求的条件,则购买它(每个购买的加密货币 2 个外部 API 请求)然后将交易数据插入 DB(1 个内部 API 请求)
  4. 当所有密码都循环通过时,重复

我尽量简化它,因为它比这复杂一点,但这是基本的工作流程。

这工作正常,但真的很慢。每个加密 ( 2) 上的循环大约需要一分钟才能完成(每个加密大约 2.5 秒)。

这里有一些代码可以让您了解结构(同样,简化到最大,因为它使用了许多其他辅助函数并且总共有几千行代码):

// Controller :
exports.strategyBacktesting = async (req, res, next) => {
    //... Some code ...

    const markets = await getMarkets();
    const calculationsResults = await calculations(markets);

    //... More code ...

    res.status(200).json({
        // Return calculationResults and other stuff for the UI
    )};
}


//----- Files in utils folders

// Called from controller
exports.getMarkets = async () => {
    // Get all the listed cryptos via an external API request
    // Loop through all the fetched data to filter the cryptos I want to work with
    // Return a Promise (array containing all the cryptos I will do the calculations on)
}

// Called from controller
exports.calculations = async (markets) => {
    // Loop through all the results from getMarkets() (markets param) (+150 results) = all the cryptos to work with

    for (let cryptoPair in markets) ...
    
    // In the loop:
       // Call the getPairCandles() function (below) to get all the data needed per crypto :

       // Note that the cryptoPair param is the object from the loop 
       const { /* data needed for the calculation */ } = await getPairCandles(cryptoPair)
     
       // Perform all the needed calculations (one iteration = one crypto) => This is where it takes a long time (around 2.5 seconds per crypto)
           // Calls lots of async helper functions and do the calculations
      

    // If some required conditions are met, do :
      //- 1 external async API call to buy the crypto 
      //- 1 external async API call to set a sell limit
      //- One internal async API call to save the trade info in the DB

    // When the loop is done on the +150 cryptos, return a Promise for the controller to return to UI
}

// Called from calculations() function above
const getPairCandles = async (cryptoPair) => {
    // Make an external API request to get specific real-time data about one crypto (the cryptoPair param of the function)
    // Loop through some data in the object received to filter the wanted properties
    // Return a Promise containing 5 arrays (the data I need to calculate on this crypto)
}

workers在 Nodejs 中读到了一些可以帮助进行繁重计算的内容。话虽如此,我该如何实施呢?就我而言,这甚至是一个好的解决方案吗?问题是,执行计算的循环是相同的,其中包含对async返回函数PromisesasyncAPI 调用的大量调用。这是大约需要一分钟才能完成的循环。

所以我认为我可以大大提高性能,但不知道如何。我能做些什么呢?有人可以指导我朝好的方向吗?

非常感谢

4

0 回答 0