Beispiel #1
0
class ApiMetaAdapter:
    """Adapter of adapters for all API instantiations"""
    def __init__(self, api_classes):
        self.apis = []  # type: list
        self.wsocks = []  # type: list

        # Extract configuration necessary to generate api adapters
        self.conf = Conf()
        api_conf = self.conf.get_api()
        exchanges = getattr(api_conf, "exchanges", [])
        currencies = getattr(api_conf, "currencies", [])

        # Setup exchange/currency/call adapters
        exch_curr = []
        for exch in exchanges:
            for curr in currencies:
                exch_curr.append((exch, curr))

        if exch_curr:
            for val_pair in exch_curr:
                for api_class in api_classes:
                    self.create_api_adapter(api_class, *val_pair)
        else:
            for api_class in api_classes:
                self.create_api_adapter(api_class)

        for api_class in api_classes:
            self.create_ws_adapter(api_class)

    def create_ws_adapter(self, api_class):
        """Create and return an api adapter"""
        api = WsAdapterFactory()
        api.product.interface(api_class)
        self.wsocks.append(api.product)

    def create_api_adapter(self, api_class, exchange=None, market=None):
        """Create and return an api adapter"""
        api = ApiAdapterFactory()
        api.product.interface(api_class, exchange, market)
        self.apis.append(api.product)

    def run(self, callback):
        """Executed on startup of application"""
        for wsock in self.wsocks:
            wsock.run(callback)
        for api in self.apis:
            api.run(callback)

    def shutdown(self):
        """Executed on shutdown of application"""
        for wsock in self.wsocks:
            wsock.run()
        for api in self.apis:
            api.shutdown()
Beispiel #2
0
class AllApiContexts(metaclass=Singleton):
    """
    Shared context between API instances.
    """
    def __init__(self):
        self.contexts = {}  # type: dict
        self.conf = Conf()

    def get(self, apiname):
        """Creates a context if one doesn't exist for given API"""
        try:
            return self.contexts[apiname]
        except KeyError:
            return self.create(apiname)

    def create(self, apiname):
        """Creates a context for given API"""
        self.contexts[apiname] = ApiContext()
        conf = self.conf.get_api(apiname)
        conf["currencies"] = self.conf.get_currencies()
        self.contexts[apiname].populate(conf)
        return self.contexts[apiname]