Skip to content

Commit

Permalink
Merge pull request #15 from olned/develop
Browse files Browse the repository at this point in the history
L2 Bitfinex orderbook
  • Loading branch information
olned authored Jun 5, 2020
2 parents 6564aea + e736a62 commit 41a07c7
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 1 deletion.
56 changes: 56 additions & 0 deletions examples/bitfinex_book.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#!/usr/bin/env python
import asyncio
import logging

from ssc2ce.bitfinex import Bitfinex, L2Book

logging.basicConfig(format='%(asctime)s %(name)s %(funcName)s %(levelname)s %(message)s', level=logging.INFO)
logger = logging.getLogger("bitfinex-basic-example")

conn = Bitfinex()


class BookMaintainer:
def __init__(self, instrument):
self.book = L2Book(instrument)
self.check_sum = None
self.active = False
self.top_bid = [0, 0]
self.top_ask = [0, 0]

async def handle_book(self, message, connector):
if type(message[1]) is str:
if message[1] == "cs":
pass
elif len(message[1]) == 3:
self.book.handle_update(message)
self.book.time = message[-1]
else:
self.book.handle_snapshot(message)
self.book.time = message[-1]

if self.top_ask[0] != self.book.asks[0][0] or self.top_ask[0] != self.book.asks[0][0]:
self.top_ask = self.book.asks[0].copy()
self.top_bid = self.book.bids[0].copy()
print(f"{self.book.instrument} bid:{self.top_bid[0]} ask:{self.top_ask[0]}")


btc = BookMaintainer("BTC-USD")
eth = BookMaintainer("ETH-USD")


async def subscribe():
await conn.subscribe({'channel': "book", 'symbol': "tBTCUSD"}, handler=btc.handle_book)
await conn.subscribe({'channel': "book", 'symbol': "tETHUSD"}, handler=eth.handle_book)


conn.on_connect_ws = subscribe

loop = asyncio.get_event_loop()

try:
loop.run_until_complete(conn.run_receiver())
except KeyboardInterrupt:
loop.run_until_complete(conn.stop())
finally:
print("Application closed")
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

setuptools.setup(
name='ssc2ce',
version="0.10.0",
version="0.11.0",
author='Oleg Nedbaylo',
author_email='[email protected]',
description='A Set of Simple Connectors for access To Cryptocurrency Exchanges',
Expand Down
1 change: 1 addition & 0 deletions ssc2ce/bitfinex/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .bitfinex import Bitfinex
from .l2_book import L2Book
54 changes: 54 additions & 0 deletions ssc2ce/bitfinex/l2_book.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import logging
from ssc2ce.common.abstract_l2_book import AbstractL2Book
from collections import deque

from ssc2ce.common.exceptions import BrokenOrderBook


class L2Book(AbstractL2Book):
change_id = None
timestamp = None
logger = logging.getLogger(__name__)

def __init__(self, instrument: str):
"""
:param instrument:
"""
AbstractL2Book.__init__(self, instrument)

def handle_snapshot(self, message: dict) -> None:
"""
:param message:
:return:
"""
self.asks.clear()
self.bids.clear()

for item in message[1]:
price = item[2]
if price < 0:
self.asks.add([item[0], -price])
else:
self.bids.add([item[0], price])

def handle_update(self, message: dict) -> None:
"""
:param message:
:return:
"""
price = message[1][0]
size = message[1][2]
count = message[1][1]
if size < 0:
if count == 0:
self._asks.update(price, 0.)
else:
self._asks.update(price, -size)
else:
if count == 0:
self._bids.update(price, 0.)
else:
self._bids.update(price, size)

0 comments on commit 41a07c7

Please sign in to comment.