同时执行多个Python类实例

发布于 2025-01-14 18:05:44 字数 6625 浏览 4 评论 0原文

我正在开发一个基本的交易机器人作为课程项目的介绍。它实现了一个 TradingBot 类并包含 trade(self) 方法。我有多个实例(t_account01、t_account02...),它们采用不同的 API 密钥、符号、间隔和各种其他值。如果我只执行一个实例,例如 t_account01.trade(),我将得到以下输出:

Time Program Started: 2022-03-15 12:17:02.143325

Initial Balance: 50000

Order Size: 18.68

Threading count: 23

Open Price: 39101

最后价格:39122.0

变化百分比:0.0537 %

线程数:37

开盘价:39101

最后价:39124.5

等。

类中的这种交易方法本质上是在程序启动时根据特定 API 密钥的余额输出余额、开始时间和订单大小。此外,它还会根据给定的时间间隔、给定的交易品种不断检查蜡烛的开盘价,将其与当前价格进行比较并计算百分比。如果达到特定百分比,则会执行交易。

理论上,它在运行一个实例时工作得很好,但是当运行两个或多个实例时,只有第一个实例出现在运行窗口中,我不确定其他实例是否也同时运行,因为只有第一个实例出现。我试图让多个实例同时运行(永远或直到我停止它),但是我不确定,因为我在代码主体中尝试的方式(如下所示)似乎不起作用。理想情况下,我希望看到每个实例输出的所有数据,但我感觉这是不可能的。 (我省略了一堆其他方法,只包含了交易方法和敏感的 api 密钥)。

class TradingBot:

    def __init__(self, ENDPOINT_REAL_PUBLIC, ENDPOINT_REAL, HTTP_ADDRESS, MAX_ORDER_SIZE, API_KEY, API_SECRET, AVAIL_BAL_REQ,
                 LEVERAGE, SYMBOL, INTERVAL, PERC_CHANGE, PERC_EXIT, STOP_LOSS, SLEEP_OPEN):
        self.INTERVAL = INTERVAL
        self.ENDPOINT_REAL_PUBLIC = ENDPOINT_REAL_PUBLIC
        self.ENDPOINT_REAL = ENDPOINT_REAL
        self.SYMBOL = SYMBOL
        self.LEVERAGE = LEVERAGE
        self.MAX_ORDER_SIZE = MAX_ORDER_SIZE
        self.STOP_LOSS = STOP_LOSS
        self.AVAIL_BAL_REQ = AVAIL_BAL_REQ
        self.PERC_CHANGE = PERC_CHANGE
        self.PERC_EXIT = PERC_EXIT
        self.SLEEP_OPEN = SLEEP_OPEN
        self.API_KEY = API_KEY
        self.API_SECRET = API_SECRET
        self.HTTP_ADDRESS = HTTP_ADDRESS
        self.session = HTTP(self.HTTP_ADDRESS,  # for MAINNET: https://api.bybit.com
                       api_key=self.API_KEY,  # Testnet API
                       api_secret=self.API_SECRET)  # Testnet Secret
        self.ws = WebSocket(
            endpoint=self.ENDPOINT_REAL,  # for MAINNET: wss://stream.bybit.com/realtime
            subscriptions=['order', 'position'],
            api_key=self.API_KEY,  # Testnet API
            api_secret=self.API_SECRET,  # Testnet Secret
            ping_interval=30,
            ping_timeout=None,
            restart_on_error=True)


    def trade(self):
        self.set_leverage()

        print()
        print("Time Program Started: ", self.current_date_time())
        print("Initial Balance: ", self.avail_balance_calc())
        print("Order Size: ", self.order_size_calc())
        print()


        count = 0
        while count < 11:
            self.open_position_size()
            self.open_position_price()
            self.open_position_size_short()
            self.open_position_price_short()

            print("Threading count: ", threading.active_count())
            if threading.active_count() >= 1750:  # 2000 is approx max thread count
                subprocess.call([sys.executable, os.path.realpath(__file__)] + sys.argv[1:])

            if (self.open_position_size() == 0) and (self.open_position_size_short() == 0) and (self.avail_balance_calc() > self.AVAIL_BAL_REQ):
                print("Open Price: ", self.open_price_calc())
                print("Last Price: ", self.last_price_calc())
                print("Percentage Change: ", round((self.perc_change_calc() * 100), 4), "%")

                # LONG ORDER & POSITION
                if self.perc_change_calc() >= self.PERC_CHANGE:
                    self.market_long_order()

                    # Position Info
                    self.open_position_size()
                    self.open_position_price()
                    print("Open Position Size: ", self.open_position_size())
                    print("Open Position Entry Price: ", self.open_position_price())

                    # Limit long close position
                    limitPriceLong = round((self.open_position_price() * self.PERC_EXIT))
                    print(self.session.place_active_order(
                        symbol=self.SYMBOL,
                        side="Sell",
                        order_type="Limit",
                        qty=self.open_position_size(),
                        price=limitPriceLong,
                        time_in_force="GoodTillCancel",
                        reduce_only=True,  # true means close order, false means open position
                        close_on_trigger=True
                    ))
                    count += 1
                    print("Current trade count: ", count)
                    time.sleep(self.SLEEP_OPEN)  # sleep 2 minutes (120 seconds)

                # SHORT ORDER & POSITION
                if self.perc_change_calc() <= (-self.PERC_CHANGE):
                    self.market_short_order()

                    # Position Info
                    self.open_position_size_short()
                    self.open_position_price_short()
                    print("Open Position Size: ", self.open_position_size_short())
                    print("Open Position Entry Price: ", self.open_position_price_short())

                    # Limit close position
                    limitPriceShort = round((self.open_position_price_short() / self.PERC_EXIT))
                    print(self.session.place_active_order(
                        symbol=self.SYMBOL,
                        side="Buy",
                        order_type="Limit",
                        qty=self.open_position_size_short(),
                        price=limitPriceShort,
                        time_in_force="GoodTillCancel",
                        reduce_only=True,  # true means close order, false means open position
                        close_on_trigger=True
                    ))
                    count += 1
                    print("Current trade count: ", count)
                    time.sleep(self.SLEEP_OPEN)  # sleep 2 minutes (120 seconds)

        print()
        print("Total trade count: ", count)
        print("Program has reached maximum amount of trades")
        print()
        print("Time Program Ended: ", self.current_date_time())
        print("Final Balance: ", self.avail_balance_calc())
        print()

if __name__ == "__main__":

    t_account01 = TradingBot("wss:...",'wss:...',"https:...",20,'API','API',2500,15,"BTCUSDT","candle.5.BTCUSDT",0.0025,1.0005,1.0005,300)
    t_account02 = TradingBot("wss:...",'wss:...',"https:...",20,'API','API',2500,15,"BTCUSDT","candle.5.BTCUSDT",0.0025,1.0010,1.0010,300)
    t_account03 = TradingBot("wss:...",'wss:...',"https:...",20,'API','API',2500,15,"BTCUSDT","candle.5.BTCUSDT",0.0030,1.0010,1.0010,300)

    
    t_account01.trade()
    t_account02.trade()
    t_account03.trade()

I am working on a basic trading bot as an intro to classes project. It implements a class TradingBot and contains the method trade(self). I have multiple instances (t_account01, t_account02...)that take different API keys, symbol, interval and various other values. If I execute only one instance such as t_account01.trade(), I will get this output:

Time Program Started: 2022-03-15 12:17:02.143325

Initial Balance: 50000

Order Size: 18.68

Threading count: 23

Open Price: 39101

Last Price: 39122.0

Percentage Change: 0.0537 %

Threading count: 37

Open Price: 39101

Last Price: 39124.5

etc.

This trade method within the class is essentially outputting the balance, start time and order size based on balance for a specific API key at the start of the program. Additionally, it is constantly checking the opening price of a candle based on the given interval, of a given symbol, comparing it to the current price and calculating the percentage. If it attains a specific percentage then it executes a trade.

In theory, it works just fine when running one instance, but when running two or more, only the first instance appears in the run window and I am unsure if the others are also simultaneously running as only the first instance appears. I am trying to get multiple instances running at the same time (forever or until i stop it) however I am unsure as the way I have tried as shown below in the main of the code does not seem to work. Ideally I would like to see all the data being outputted for each instance but I have a feeling it is not possible. (I omitted a bunch of other methods and only included the trade method for shortness along with the sensitive api keys).

class TradingBot:

    def __init__(self, ENDPOINT_REAL_PUBLIC, ENDPOINT_REAL, HTTP_ADDRESS, MAX_ORDER_SIZE, API_KEY, API_SECRET, AVAIL_BAL_REQ,
                 LEVERAGE, SYMBOL, INTERVAL, PERC_CHANGE, PERC_EXIT, STOP_LOSS, SLEEP_OPEN):
        self.INTERVAL = INTERVAL
        self.ENDPOINT_REAL_PUBLIC = ENDPOINT_REAL_PUBLIC
        self.ENDPOINT_REAL = ENDPOINT_REAL
        self.SYMBOL = SYMBOL
        self.LEVERAGE = LEVERAGE
        self.MAX_ORDER_SIZE = MAX_ORDER_SIZE
        self.STOP_LOSS = STOP_LOSS
        self.AVAIL_BAL_REQ = AVAIL_BAL_REQ
        self.PERC_CHANGE = PERC_CHANGE
        self.PERC_EXIT = PERC_EXIT
        self.SLEEP_OPEN = SLEEP_OPEN
        self.API_KEY = API_KEY
        self.API_SECRET = API_SECRET
        self.HTTP_ADDRESS = HTTP_ADDRESS
        self.session = HTTP(self.HTTP_ADDRESS,  # for MAINNET: https://api.bybit.com
                       api_key=self.API_KEY,  # Testnet API
                       api_secret=self.API_SECRET)  # Testnet Secret
        self.ws = WebSocket(
            endpoint=self.ENDPOINT_REAL,  # for MAINNET: wss://stream.bybit.com/realtime
            subscriptions=['order', 'position'],
            api_key=self.API_KEY,  # Testnet API
            api_secret=self.API_SECRET,  # Testnet Secret
            ping_interval=30,
            ping_timeout=None,
            restart_on_error=True)


    def trade(self):
        self.set_leverage()

        print()
        print("Time Program Started: ", self.current_date_time())
        print("Initial Balance: ", self.avail_balance_calc())
        print("Order Size: ", self.order_size_calc())
        print()


        count = 0
        while count < 11:
            self.open_position_size()
            self.open_position_price()
            self.open_position_size_short()
            self.open_position_price_short()

            print("Threading count: ", threading.active_count())
            if threading.active_count() >= 1750:  # 2000 is approx max thread count
                subprocess.call([sys.executable, os.path.realpath(__file__)] + sys.argv[1:])

            if (self.open_position_size() == 0) and (self.open_position_size_short() == 0) and (self.avail_balance_calc() > self.AVAIL_BAL_REQ):
                print("Open Price: ", self.open_price_calc())
                print("Last Price: ", self.last_price_calc())
                print("Percentage Change: ", round((self.perc_change_calc() * 100), 4), "%")

                # LONG ORDER & POSITION
                if self.perc_change_calc() >= self.PERC_CHANGE:
                    self.market_long_order()

                    # Position Info
                    self.open_position_size()
                    self.open_position_price()
                    print("Open Position Size: ", self.open_position_size())
                    print("Open Position Entry Price: ", self.open_position_price())

                    # Limit long close position
                    limitPriceLong = round((self.open_position_price() * self.PERC_EXIT))
                    print(self.session.place_active_order(
                        symbol=self.SYMBOL,
                        side="Sell",
                        order_type="Limit",
                        qty=self.open_position_size(),
                        price=limitPriceLong,
                        time_in_force="GoodTillCancel",
                        reduce_only=True,  # true means close order, false means open position
                        close_on_trigger=True
                    ))
                    count += 1
                    print("Current trade count: ", count)
                    time.sleep(self.SLEEP_OPEN)  # sleep 2 minutes (120 seconds)

                # SHORT ORDER & POSITION
                if self.perc_change_calc() <= (-self.PERC_CHANGE):
                    self.market_short_order()

                    # Position Info
                    self.open_position_size_short()
                    self.open_position_price_short()
                    print("Open Position Size: ", self.open_position_size_short())
                    print("Open Position Entry Price: ", self.open_position_price_short())

                    # Limit close position
                    limitPriceShort = round((self.open_position_price_short() / self.PERC_EXIT))
                    print(self.session.place_active_order(
                        symbol=self.SYMBOL,
                        side="Buy",
                        order_type="Limit",
                        qty=self.open_position_size_short(),
                        price=limitPriceShort,
                        time_in_force="GoodTillCancel",
                        reduce_only=True,  # true means close order, false means open position
                        close_on_trigger=True
                    ))
                    count += 1
                    print("Current trade count: ", count)
                    time.sleep(self.SLEEP_OPEN)  # sleep 2 minutes (120 seconds)

        print()
        print("Total trade count: ", count)
        print("Program has reached maximum amount of trades")
        print()
        print("Time Program Ended: ", self.current_date_time())
        print("Final Balance: ", self.avail_balance_calc())
        print()

if __name__ == "__main__":

    t_account01 = TradingBot("wss:...",'wss:...',"https:...",20,'API','API',2500,15,"BTCUSDT","candle.5.BTCUSDT",0.0025,1.0005,1.0005,300)
    t_account02 = TradingBot("wss:...",'wss:...',"https:...",20,'API','API',2500,15,"BTCUSDT","candle.5.BTCUSDT",0.0025,1.0010,1.0010,300)
    t_account03 = TradingBot("wss:...",'wss:...',"https:...",20,'API','API',2500,15,"BTCUSDT","candle.5.BTCUSDT",0.0030,1.0010,1.0010,300)

    
    t_account01.trade()
    t_account02.trade()
    t_account03.trade()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文