Apply fixes and refactoring to the bfxapi.handlers sub-package.

This commit is contained in:
Davide Casale
2023-02-14 16:29:50 +01:00
parent f0f150cec2
commit 17c9502733
3 changed files with 32 additions and 24 deletions

View File

@@ -58,4 +58,11 @@ class InvalidAuthenticationCredentials(BfxWebsocketException):
This error indicates that the user has provided incorrect credentials (API-KEY and API-SECRET) for authentication.
"""
pass
class HandlerNotFound(BfxWebsocketException):
"""
This error indicates that a handler was not found for an incoming message.
"""
pass

View File

@@ -1,10 +1,8 @@
from typing import List
from ..types import *
from .. import serializers
from ..exceptions import BfxWebsocketException
from .. types import *
from .. exceptions import HandlerNotFound
class AuthenticatedChannelsHandler(object):
__abbreviations = {
@@ -37,7 +35,7 @@ class AuthenticatedChannelsHandler(object):
*list(__abbreviations.values())
]
def __init__(self, event_emitter, strict = False):
def __init__(self, event_emitter, strict = True):
self.event_emitter, self.strict = event_emitter, strict
def handle(self, type, stream):
@@ -52,20 +50,20 @@ class AuthenticatedChannelsHandler(object):
return self.event_emitter.emit(event, [ serializer.parse(*substream) for substream in stream ])
return self.event_emitter.emit(event, serializer.parse(*stream))
if self.strict == True:
raise BfxWebsocketException(f"Event of type <{type}> not found in self.__handlers.")
if self.strict:
raise HandlerNotFound(f"No handler found for event of type <{type}>.")
def __notification(self, stream):
type, serializer = "notification", serializers._Notification(serializer=None)
if stream[1] == "on-req" or stream[1] == "ou-req" or stream[1] == "oc-req":
type, serializer = f"{stream[1]}-notification", serializers._Notification[Order](serializer=serializers.Order)
type, serializer = f"{stream[1]}-notification", serializers._Notification(serializer=serializers.Order)
if stream[1] == "oc_multi-req":
type, serializer = f"{stream[1]}-notification", serializers._Notification[List[Order]](serializer=serializers.Order, iterate=True)
type, serializer = f"{stream[1]}-notification", serializers._Notification(serializer=serializers.Order, iterate=True)
if stream[1] == "fon-req" or stream[1] == "foc-req":
type, serializer = f"{stream[1]}-notification", serializers._Notification[FundingOffer](serializer=serializers.FundingOffer)
type, serializer = f"{stream[1]}-notification", serializers._Notification(serializer=serializers.FundingOffer)
return self.event_emitter.emit(type, serializer.parse(*stream))

View File

@@ -1,8 +1,8 @@
from ..types import *
from .. import serializers
from ..enums import Channels
from .. types import *
from .. exceptions import HandlerNotFound
class PublicChannelsHandler(object):
EVENTS = [
@@ -13,23 +13,26 @@ class PublicChannelsHandler(object):
"derivatives_status_update",
]
def __init__(self, event_emitter):
self.event_emitter = event_emitter
def __init__(self, event_emitter, strict = True):
self.event_emitter, self.strict = event_emitter, strict
self.__handlers = {
Channels.TICKER: self.__ticker_channel_handler,
Channels.TRADES: self.__trades_channel_handler,
Channels.BOOK: self.__book_channel_handler,
Channels.CANDLES: self.__candles_channel_handler,
Channels.STATUS: self.__status_channel_handler
"ticker": self.__ticker_channel_handler,
"trades": self.__trades_channel_handler,
"book": self.__book_channel_handler,
"candles": self.__candles_channel_handler,
"status": self.__status_channel_handler
}
def handle(self, subscription, *stream):
_clear = lambda dictionary, *args: { key: value for key, value in dictionary.items() if key not in args }
if channel := subscription["channel"] or channel in self.__handlers.keys():
if (channel := subscription["channel"]) and channel in self.__handlers.keys():
return self.__handlers[channel](_clear(subscription, "event", "channel", "subId"), *stream)
if self.strict:
raise HandlerNotFound(f"No handler found for channel <{subscription['channel']}>.")
def __ticker_channel_handler(self, subscription, *stream):
if subscription["symbol"].startswith("t"):
return self.event_emitter.emit(
@@ -46,7 +49,7 @@ class PublicChannelsHandler(object):
)
def __trades_channel_handler(self, subscription, *stream):
if type := stream[0] or type in [ "te", "tu", "fte", "ftu" ]:
if (type := stream[0]) and type in [ "te", "tu", "fte", "ftu" ]:
if subscription["symbol"].startswith("t"):
return self.event_emitter.emit(
{ "te": "t_trade_executed", "tu": "t_trade_execution_update" }[type],