Network

The network subpackage provides low-level base components for networking clients.

The base classes can be inherited to assist with writing adapters for integrations with exchanges, brokerages, data providers/feeds and other venues or services.

class HttpClient ( loop: asyncio.AbstractEventLoop , Logger logger , list addresses=None , list nameservers=None , int ttl_dns_cache=86400 , ssl_context: Optional[SSLContext] = None , ssl: Optional[Union[bool , Fingerprint , SSLContext]] = None , dict connector_kwargs=None , int latency_qsize=1000 )

Bases: object

Provides an asynchronous HTTP client.

Parameters :
  • loop ( asyncio.AbstractEventLoop ) – The event loop for the client.

  • logger ( Logger ) – The logger for the client.

  • ttl_dns_cache ( int ) – The time to live for the DNS cache.

  • ssl ( Union [ None , bool , Fingerprint , SSLContext ] , default False ) – The ssl context to use for HTTPS.

  • connector_kwargs ( dict , optional ) – The connector key word arguments.

  • latency_qsize ( int , default 1000 ) – The maxlen for the internal latencies deque.

Raises :
  • ValueError – If ttl_dns_cache is not positive (> 0).

  • ValueError – If latency_qsize is not position (> 0).

avg_latency ( self ) uint64_t

Return the average round-trip latency (nanoseconds) for this client.

Many factors will affect latency including which endpoints are hit and server side processing time. If no latencies recorded yet, then will return zero.

Returns :

uint64_t

async connect ( self ) None

Connect the HTTP client session.

connected

Return whether the HTTP client is connected.

Returns :

bool

async delete ( self , unicode url: str , dict headers: Optional[dict[str , str]] = None , **kwargs ) ClientResponse
async disconnect ( self ) None

Disconnect the HTTP client session.

async get ( self , unicode url: str , dict headers: Optional[dict[str , str]] = None , **kwargs ) ClientResponse
max_latency ( self ) uint64_t

Return the maximum round-trip latency (nanoseconds) for this client.

Many factors will affect latency including which endpoints are hit and server side processing time. If no latencies recorded yet, then will return zero.

Returns :

uint64_t

min_latency ( self ) uint64_t

Return the minimum round-trip latency (nanoseconds) for this client.

Many factors will affect latency including which endpoints are hit and server side processing time. If no latencies recorded yet, then will return zero.

Returns :

uint64_t

async post ( self , unicode url: str , dict headers: Optional[dict[str , str]] = None , **kwargs ) ClientResponse
async request ( self , unicode method: str , unicode url: str , dict headers: Optional[dict[str , str]] = None , dict json: Optional[dict[str , Any]] = None , **kwargs ) ClientResponse
session

Return the current HTTP client session.

Returns :

aiohttp.ClientSession

class SocketClient ( loop: asyncio.AbstractEventLoop , Logger logger: Logger , host , port , handler: Callable , bool ssl=True , bytes crlf=None , unicode encoding=u'utf-8' )

Bases: object

Provides a low-level generic socket base client.

Parameters :
  • loop ( asyncio.AbstractEventLoop ) – The event loop for the client.

  • logger ( Logger ) – The logger for the client.

  • host ( str ) – The host for the client.

  • port ( int ) – The port for the client.

  • handler ( Callable ) – The handler to process the raw bytes read.

  • ssl ( bool ) – If SSL should be used for socket connection.

  • crlf ( bytes , optional ) – The carriage return, line feed delimiter on which to split messages.

  • encoding ( str , optional ) – The encoding to use when sending messages.

Raises :
  • ValueError – If host is not a valid string.

  • ValueError – If port is not positive (> 0).

async connect ( self )
async disconnect ( self )
host

The host for the socket client.

Returns :

str

is_connected

If the client is connected.

Returns :

bool

is_running

If the client is running.

Returns :

bool

is_stopping

If the client is stopping.

Returns :

bool

port

The port for the socket client.

Returns :

int

async post_connection ( self )

The actions to perform post-connection. i.e. sending further connection messages.

async post_disconnection ( self ) None

Actions to be performed post disconnection.

async post_reconnection ( self ) None

Actions to be performed post reconnection.

async reconnect ( self )
async send ( self , bytes raw )
ssl

If the socket client is using SSL.

Returns :

bool

async start ( self )
class WSMsgType ( value , names = None , * , module = None , qualname = None , type = None , start = 1 , boundary = None )

Bases: IntFlag

as_integer_ratio ( )

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count ( )

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length ( )

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate ( )

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

from_bytes ( byteorder = 'big' , * , signed = False )

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use ` sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Indicates whether two’s complement is used to represent the integer.

imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes ( length = 1 , byteorder = 'big' , * , signed = False )

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use ` sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

class WebSocketClient ( loop: asyncio.AbstractEventLoop, Logger logger: Logger, handler: Callable[[bytes], None], int max_retry_connection=0, bytes pong_msg=None, bool log_send=False, bool log_recv=False )

Bases: object

Provides a low-level web socket base client.

Parameters :
  • loop ( asyncio.AbstractEventLoop ) – The event loop for the client.

  • logger ( LoggerAdapter ) – The logger adapter for the client.

  • handler ( Callable [ [ bytes ] , None ] ) – The handler for receiving raw data.

  • max_retry_connection ( int , default 0 ) – The number of times to attempt a reconnection.

  • pong_msg ( bytes , optional ) – The pong message expected from the server (used to filter).

  • log_send ( bool , default False ) – If the raw sent bytes for each message should be logged.

  • log_recv ( bool , default False ) – If the raw recv bytes for each message should be logged.

async close ( self )
async connect ( self , unicode ws_url , bool start=True , **ws_kwargs ) None

Connect the WebSocket client.

Will call post_connection() prior to starting receive loop.

Parameters :
  • ws_url ( str ) – The endpoint URL to connect to.

  • start ( bool , default True ) – If the WebSocket should start its receive loop.

  • ws_kwargs ( dict ) – The optional kwargs for connection.

Raises :

ValueError – If ws_url is not a valid string.

connection_retry_count

The current connection retry count.

Returns :

int

async disconnect ( self ) None

Disconnect the WebSocket client session.

Will call post_disconnection() .

is_connected

If the client is connected.

Returns :

bool

is_running

If the client is running.

Returns :

bool

is_stopping

If the client is stopping.

Returns :

bool

max_retry_connection

The max connection retries.

Returns :

int

async post_connection ( self ) None

Actions to be performed post connection.

async post_disconnection ( self ) None

Actions to be performed post disconnection.

async post_reconnection ( self ) None

Actions to be performed post reconnection.

async receive ( self ) Optional [ bytes ]
async reconnect ( self ) None

Reconnect the WebSocket client session.

Will call post_reconnection() following connection.

async send ( self , bytes raw ) None
async send_json ( self , dict msg ) None
async start ( self ) None
unknown_message_count

The current unknown message count.

Returns :

int