import ccxt


def test_public_endpoints(exchange_id, symbol):
    try:
        exchange_class = getattr(ccxt, exchange_id)
        exchange = exchange_class()

        # Check and test fetch_ticker
        if exchange.has.get('fetchTicker', False):
            exchange.fetch_ticker(symbol)

        # Check and test fetch_tickers
        if exchange.has.get('fetchTickers', False):
            exchange.fetch_tickers([symbol])

        # Check and test fetch_order_book
        if exchange.has.get('fetchOrderBook', False):
            exchange.fetch_order_book(symbol)

        # Check and test fetch_trades
        if exchange.has.get('fetchTrades', False):
            exchange.fetch_trades(symbol)

        # Check and test fetch_ohlcv
        if exchange.has.get('fetchOHLCV', False):
            timeframe = '1m'
            since = exchange.parse8601('2022-01-01T00:00:00Z')
            exchange.fetch_ohlcv(symbol, timeframe, since)

        return True
    except Exception as e:
        print(f"Exchange {exchange_id} failed: {e}")
        return False


# List of all supported exchanges
exchange_ids = ccxt.exchanges

# Symbol to test (using a common symbol that is likely available on many exchanges)
test_symbol = 'BTC/USDT'

# Dictionary to store the exchanges that support public market data endpoints
working_exchanges = []

# Iterate through each exchange and test public endpoints
for exchange_id in exchange_ids:
    print(f"Testing exchange: {exchange_id}")
    if test_public_endpoints(exchange_id, test_symbol):
        working_exchanges.append(exchange_id)

# Print the working exchanges
print("Exchanges with working public market data endpoints:")
for exchange in working_exchanges:
    print(exchange)

# Optionally save the results to a file
with open('working_public_exchanges.txt', 'w') as f:
    for exchange in working_exchanges:
        f.write(f"{exchange}\n")
