I have some basic class Trader
in trader.py
:
class Trader(object):
def __init__(self, exchange_name, api_key, api_secret):
self.Exchange = Exchange(exchange_name, api_key, api_secret).exchange
and a class Exchange
in exchange.py
class Exchange(object):
def __init__(self, name, api_key, api_secret):
self.name = name
exchange_id = name
exchange_class = getattr(ccxt, exchange_id)
self.exchange = exchange_class({
'apiKey': api_key,
'secret': api_secret,
'timeout': 30000,
'enableRateLimit': True,
})
The above works. So I can use self.Exchange
inside the Trader class to use functions against the exchange. But it works only because of this line:
self.Exchange = Exchange(exchange_name, api_key, api_secret).exchange
I don't like the fact I have to put .exchange after it. I'm just a bit playing and learning python. I'm not very experienced in python programming / I'm also not a coin trader, but I liked the ccxt package.
How can I make this work without needing to putting the .exchange
behind my Exchange(...) or is this normal behaviour? Or do I have to make my exchange class in a different way?
Thanks
Since exchange
is an attribute of an instance of the Exchange
class, this is normal behavior.
If you want to access exchange
without needing to put .exchange
after your Exchange
object, you might consider doing away with the Exchange
class entirely—since it seems you only use it to get the instance of the exchange_class
from ccxt—and writing a function instead.
Here's an example:
def get_exchange(exchange_name, api_key, api_secret):
exchange_class = getattr(ccxt, exchange_id)
return exchange_class({
'apiKey': api_key,
'secret': api_secret,
'timeout': 30000,
'enableRateLimit': True,
})
class Trader:
def __init__(self, exchange_name, api_key, api_secret):
self.exchange = get_exchange(exchange_name, api_key, api_secret)
This way an exchange
will be accessible directly by instances of Trader
.