Closing all positions before 10 minutes to end market day

Hello there!

This code obliges you to close all positions at the end of the trading session (10 minutes before the US Market closes). Docs: Clock | Alpaca Docs

            current_time = api.get_clock().timestamp.timestamp()
            closing_time = api.get_clock().next_close.timestamp()
            future_time = current_time + (10 * 60) // 600 sec

            if future_time > closing_time:
                try:
                    portfolio = api.list_positions()

                    for position in portfolio:

                        self.alpaca.close_position(position.symbol)
                        time.sleep(1)

                except Exception as e:
                    logger.error(f"--- ERROR --- {e} ---")                               
            else:
                // call to trade function

Output:

current_time: 1672443283
closing_time: 1672779600 
future_time:  1672443883

At first glance, it seems that everything is in order, the metric data was received after the closing of the trading (market) session. Please help me understand why this is happening…
Thanks.

if future_time > closing_time:

This will be true indefinitely after the first time it is true. This means your loop to gather positions and close them will run however often that code block is called. If this is in a while loop, it can mean you are calling it many times, even after the market closes.

        market_open = True
        while market_open == True:
            time.sleep(self.sleeper * 60)

            current_time = self.alpaca.get_clock().timestamp.timestamp()
            closing_time = self.alpaca.get_clock().next_close.timestamp()
            future_time = current_time + (self.sleeper * 60)

            if closing_time < future_time:
                try:
                    portfolio = self.alpaca.list_positions()

                    for position in portfolio:
                        self.alpaca.close_position(position.symbol)
                        time.sleep(1)

                   # call isMarketOpen() and sleep before market wake up

                except Exception as e:
                    logger.error(f"--- ERROR --- : {e} ---")                               
            else:
                # call trade function

As far as I understand the your logic.