Search code examples
pythonccxt

How to run multiple functions and create a list?


I'm new to Python and I have a list of crypto exchanges I would like to connect with the ccxt library in order to fetch OHLC data.

But instead to instantiate each exchanges classes one by one (many objects), I would like to create an exchanges object containing all the exchanges data in a list, so that I could request data of the first exchange with exchanges[0], data from the second with exchanges[1], etc.

import ccxt # import module

ex_bitfinex = ccxt.bitfinex()
ex_binance = ccxt.binance()
ex_okcoinusd = ccxt.okcoinusd()
...

ex = ["bitfinex",
      "binance",
      "okcoinusd"]

# This doesn't return the expected result
exchanges = ccxt.ex()

With I would use lapply() but how could I achieve this in Python?


Solution

  • Just use getattr(...) and a list comp.

    exchanges = [getattr(ccxt, e)() for e in ex] 
    

    Then you can access all three exchanges by index.