async def fetchcurrentprices(pair, exchanges): prices = {} for ex in exchanges: try:…
- 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 мнен нужны цены для фьючерсов
- 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/USDTfor perpetual futures might beBTC/USDT:USDTor 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
-
Exchange Naming: The
exin theexchangeslist must be in the format lower case and match the names recognized by CCXT. -
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:USDTorBTC-USDTetc. -
Asynchronous Support: As the code is using
asyncandawait, make sure your CCXT version supports asynchronous operations (ccxt.async_support). -
Rate Limiting: Enabling rate limits is crucial for avoiding getting banned from API usage.
-
Environment: Make sure you handle the asynchronous
close()method on the exchange instance to properly clean up resources.
Additional Enhancements
- Error Handling: This can be further enhanced by adding more granular error handling for specific types of exceptions.
- Logging: Ensure you configure logging properly to capture debug messages as needed.
- Retries: Implement retries with backoff in case of transient errors.
Run the above
mainfunction 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. -
- 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
- 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 likeaiodns. Instead, you need to use theSelectorEventLoop.To solve this, you can set the
SelectorEventLoopexplicitly 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
-
Setting Event Loop Policy:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())ensures that theSelectorEventLoopis used on Windows. This resolves the compatibility issue withaiodns.
-
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
aiodnsissue. -