如何在自定义变量或属性上调用CCXT的fetch_ticker等方法?
如何在自定义Exchange类中调用CCXT的各类方法?
问题背景
我是Python及软件开发领域的新手,已编写如下代码实现通过自定义参数连接CCXT库:
class Exchange: """ docstring goes here """ def __init__(self, ex_name): self.name = ex_name ex_obj = getattr(ccxt, ex_name) self.ex = ex_obj({ 'enableRateLimit': True }) print(self.ex) # just for checking connection Exchange('binance')
我希望实现类似如下代码的效果,直接调用CCXT的各类方法:
exchange = ccxt.binance() print(exchange.fetch_ticker('BTC/BUSD'))
请问如何在自定义类的变量或属性上使用CCXT的各类方法?
解决方案
你有两种简单的方式实现这个需求:
方式1:直接调用类中存储的CCXT实例属性
你的Exchange类已经把CCXT的交易所实例存在了self.ex属性里,直接通过这个属性调用CCXT的方法即可:
class Exchange: """ docstring goes here """ def __init__(self, ex_name): self.name = ex_name ex_obj = getattr(ccxt, ex_name) self.ex = ex_obj({ 'enableRateLimit': True }) print(self.ex) # just for checking connection # 使用示例 my_exchange = Exchange('binance') # 直接通过.ex属性调用CCXT的fetch_ticker方法 print(my_exchange.ex.fetch_ticker('BTC/BUSD'))
方式2:用__getattr__方法代理所有CCXT方法
如果不想每次都写.ex,可以给Exchange类添加一个__getattr__魔术方法,自动把未定义的方法转发给内部的CCXT实例:
class Exchange: """ docstring goes here """ def __init__(self, ex_name): self.name = ex_name ex_obj = getattr(ccxt, ex_name) self.ex = ex_obj({ 'enableRateLimit': True }) print(self.ex) # just for checking connection def __getattr__(self, name): # 当调用Exchange实例上不存在的方法时,转发给self.ex return getattr(self.ex, name) # 使用示例 my_exchange = Exchange('binance') # 直接调用方法,不需要写.ex print(my_exchange.fetch_ticker('BTC/BUSD')) # 其他CCXT方法也可以直接调用,比如 print(my_exchange.fetch_balance())
这种方式更接近你想要的原生CCXT调用体验,所有CCXT支持的方法都可以直接通过你的Exchange实例调用。
内容的提问来源于stack exchange,提问作者preacher2470
相关产品推荐
相关产品推荐

