Skip to content
The Chat Archive
gpt-4o-2024-05-13· OpenAI WildChat-4.8M (AI2)

async def fetchcurrentprices(pair, exchanges): prices = {} for ex in exchanges: try:…

  1. User

    async def fetch_current_prices(pair, exchanges): prices = {} for ex in exchanges: try: logging.debug(f"Fetching current prices for {pair} on {ex}") exchange = getattr(ccxt, ex.lower())({'enableRateLimit': True}) market = f'{pair}' if ' / ' not in pair else f'{pair}' ticker = await loop.run_in_executor(None, exchange.fetch_ticker, market) prices[ex] = { 'long': ticker['ask'], 'short': ticker['bid'] } except Exception as e: logging.error(f"Error fetching prices for {pair} on {ex}: {str(e)}") prices[ex] = f"Error: {str(e)}" return prices мнен нужны цены для фьючерсов

  2. Assistant

    To fetch prices specifically for futures, you need to make sure that the given pairs are futures trading pairs and that you are using an exchange that supports futures trading. The code snippet you provided shows how to fetch spot prices using CCXT, but fetching futures prices has a few differences.

    Below is an updated example that demonstrates how to fetch futures prices using CCXT. Note that the pair format may differ for futures, for example, BTC/USDT for perpetual futures might be BTC/USDT:USDT or other variations depending on the exchange.

    import logging
    import asyncio
    import ccxt
    import ccxt.async_support as ccxt_async
    
    async def fetch_current_futures_prices(pair, exchanges):
        prices = {}
        for ex in exchanges:
            try:
                logging.debug(f"Fetching current futures prices for {pair} on {ex}")
                exchange_class = getattr(ccxt_async, ex.lower())
                exchange = exchange_class({'enableRateLimit': True})
                market = f'{pair}' if ' / ' not in pair else f'{pair}'
                ticker = await exchange.fetch_ticker(market)
                prices[ex] = {
                    'long': ticker['ask'],
                    'short': ticker['bid']
                }
            except Exception as e:
                logging.error(f"Error fetching futures prices for {pair} on {ex}: {str(e)}")
                prices[ex] = f"Error: {str(e)}"
            finally:
                await exchange.close()
        return prices
    
    async def main():
        pair = 'BTC/USDT:USDT'  # Example for a futures contract pair
        exchanges = ['binance', 'bitmex', 'bybit']  # List of exchanges supporting futures trading
        prices = await fetch_current_futures_prices(pair, exchanges)
        print(prices)
    
    if __name__ == '__main__':
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())
    

    Things to Note

    1. Exchange Naming: The ex in the exchanges list must be in the format lower case and match the names recognized by CCXT.

    2. Pair Format: Ensure that the pair format is correct for futures trading on each specific exchange. Sometimes, exchanges have unique identifiers for futures contracts such as BTC/USDT:USDT or BTC-USDT etc.

    3. Asynchronous Support: As the code is using async and await, make sure your CCXT version supports asynchronous operations (ccxt.async_support).

    4. Rate Limiting: Enabling rate limits is crucial for avoiding getting banned from API usage.

    5. Environment: Make sure you handle the asynchronous close() method on the exchange instance to properly clean up resources.

    Additional Enhancements

    1. Error Handling: This can be further enhanced by adding more granular error handling for specific types of exceptions.
    2. Logging: Ensure you configure logging properly to capture debug messages as needed.
    3. Retries: Implement retries with backoff in case of transient errors.

    Run the above main function to test fetching the futures prices for the specified exchanges and pairs. Make sure you have the necessary permissions and API keys if required by the exchanges you are querying.

  3. User

    C:\Users\user\PycharmProjects\RATE AND UI\аннгп.py:33: DeprecationWarning: There is no current event loop loop = asyncio.get_event_loop() ERROR:root:Error fetching futures prices for BTC/USDT:USDT on binance: aiodns needs a SelectorEventLoop on Windows. See more: https://github.com/saghul/aiodns/issues/86 ERROR:root:Error fetching futures prices for BTC/USDT:USDT on okx: aiodns needs a SelectorEventLoop on Windows. See more: https://github.com/saghul/aiodns/issues/86 {'binance': 'Error: aiodns needs a SelectorEventLoop on Windows. See more: https://github.com/saghul/aiodns/issues/86', 'okx': 'Error: aiodns needs a SelectorEventLoop on Windows. See more: https://github.com/saghul/aiodns/issues/86', 'bybit': 'Error: aiodns needs a SelectorEventLoop on Windows. See more: https://github.com/saghul/aiodns/issues/86'} ERROR:root:Error fetching futures prices for BTC/USDT:USDT on bybit: aiodns needs a SelectorEventLoop on Windows. See more: https://github.com/saghul/aiodns/issues/86

  4. Assistant

    The error you are seeing is specific to how asyncio interacts with the event loop on Windows. The default event loop on Windows (ProactorEventLoop) does not play well with certain libraries like aiodns. Instead, you need to use the SelectorEventLoop.

    To solve this, you can set the SelectorEventLoop explicitly when your script is running on Windows. Modify your script as follows:

    import logging
    import asyncio
    import ccxt.async_support as ccxt_async
    import sys
    
    # Configure logging
    logging.basicConfig(level=logging.DEBUG)
    
    # Set the event loop policy to SelectorEventLoop on Windows
    if sys.platform.startswith('win'):
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    
    async def fetch_current_futures_prices(pair, exchanges):
        prices = {}
        for ex in exchanges:
            try:
                logging.debug(f"Fetching current futures prices for {pair} on {ex}")
                exchange_class = getattr(ccxt_async, ex.lower())
                exchange = exchange_class({'enableRateLimit': True})
                market = f'{pair}' if ' / ' not in pair else f'{pair}'
                ticker = await exchange.fetch_ticker(market)
                prices[ex] = {
                    'long': ticker['ask'],
                    'short': ticker['bid']
                }
            except Exception as e:
                logging.error(f"Error fetching futures prices for {pair} on {ex}: {str(e)}")
                prices[ex] = f"Error: {str(e)}"
            finally:
                await exchange.close()
        return prices
    
    async def main():
        pair = 'BTC/USDT:USDT'  # Example for a futures contract pair
        exchanges = ['binance', 'okx', 'bybit']  # List of exchanges supporting futures trading
        prices = await fetch_current_futures_prices(pair, exchanges)
        print(prices)
    
    if __name__ == '__main__':
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())
    

    Key Changes

    1. Setting Event Loop Policy:

      • asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) ensures that the SelectorEventLoop is used on Windows. This resolves the compatibility issue with aiodns.
    2. Logging:

      • Added basic logging configuration to capture debug and error messages properly.

    Running the Script

    • Make sure to test the script in a Windows environment.
    • Ensure you have all necessary dependencies installed:
      pip install ccxt aiodns
      

    With these changes, your script should work correctly on Windows without encountering the aiodns issue.