Code Monkey home page Code Monkey logo

Comments (1)

evgrmn avatar evgrmn commented on July 18, 2024

Fixed in the commit 75d1f36. When loading the trading history in the file api/bybit/agent.py in the trading_history() function, the sign of correct exit from the thread has been changed, explicitly specified as “success” at the exit point from get_in_thread(). Thus, if the get_in_thread() function does not complete due to a Bybit API error, the thread completion flag will remain by default as None, which will be regarded by the program as an unsuccessful attempt to load the trading history, and therefore will be a signal to completely reload the data from Bybit.

See comments in the code below:

def trading_history(self, histCount: int, time=None) -> list:
    if time:
        trade_history = []
        utc = datetime.now(timezone.utc)
        if utc - time > timedelta(days=729):
            self.logger.info(
                "Bybit only allows you to query trading history for the last 2 years. Check the History.ini file."
            )
            time = utc - timedelta(days=729)
            self.logger.info("Time changed to " + str(time))
        startTime = service.time_converter(time)
        limit = min(100, histCount)

        def get_in_thread(category, startTime, limit, success, num):
            nonlocal trade_history
            cursor = "no"
            while cursor:
                self.logger.info(
                    "Sending get_executions() - category - "
                    + category
                    + " - startTime - "
                    + str(service.time_converter(startTime / 1000))
                )
                result = self.session.get_executions(
                    category=category,
                    startTime=startTime,
                    limit=limit,
                    cursor=cursor,
                )
                cursor = result["result"]["nextPageCursor"]
                res = result["result"]["list"]
                if isinstance(result["result"]["list"], list):
                    for row in res:
                        row["symbol"] = (row["symbol"], category, self.name)
                        row["execID"] = row["execId"]
                        row["orderID"] = row["orderId"]
                        row["category"] = category
                        row["lastPx"] = float(row["execPrice"])
                        row["leavesQty"] = float(row["leavesQty"])
                        row["transactTime"] = service.time_converter(
                            time=int(row["execTime"]) / 1000, usec=True
                        )
                        row["commission"] = float(row["feeRate"])
                        if row["orderLinkId"]:
                            row["clOrdID"] = row["orderLinkId"]
                        row["price"] = float(row["execPrice"])
                        if category == "spot":
                            row["settlCurrency"] = (row["feeCurrency"], self.name)
                        else:
                            row["settlCurrency"] = self.Instrument[
                                row["symbol"]
                            ].settlCurrency
                        row["lastQty"] = float(row["execQty"])
                        row["market"] = self.name
                        if row["execType"] == "Funding":
                            if row["side"] == "Sell":
                                row["lastQty"] = -row["lastQty"]
                        row["execFee"] = float(row["execFee"])
                    trade_history += res
                    ####################################################
                    # success[num] is explicitly specified as “success”
                    ####################################################
                    success[num] = "success"
                else:
                    return

    while startTime < service.time_converter(datetime.now(tz=timezone.utc)):
        threads, success = [], []
        for category in self.categories:
            ####################################################
            # success[num] defaults to None
            ####################################################
            success.append(None)
            t = threading.Thread(
                target=get_in_thread,
                args=(category, startTime, limit, success, len(success) - 1),
            )
            threads.append(t)
            t.start()
        [thread.join() for thread in threads]
        ####################################################
        # All threads must succeed, otherwise None is returned
        ####################################################
        for s in success:
            if not s:
                return
        message = (
            "Bybit - loading trading history, startTime="
            + str(service.time_converter(startTime / 1000))
            + ", received: "
            + str(len(trade_history))
            + " records."
        )
        self.logger.info(message)
        if len(trade_history) > histCount:
            break
        startTime += 604800000  # +7 days
    trade_history.sort(key=lambda x: x["transactTime"])

    return trade_history

from tmatic.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.