core/bfxbot/bfxbot.py

83 lines
2.6 KiB
Python
Raw Normal View History

2020-11-30 14:38:28 +00:00
from time import sleep
2020-12-10 16:29:26 +00:00
from typing import Dict, List
2020-11-30 09:12:43 +00:00
from bfxbot.bfxwrapper import BfxWrapper
2020-11-30 14:38:28 +00:00
from bfxbot.currency import Symbol
2020-12-10 16:29:26 +00:00
from bfxbot.models import SymbolStatus, Ticker, EventHandler, Strategy, Event, EventKind
2020-11-30 09:12:43 +00:00
class BfxBot:
2020-12-10 16:29:26 +00:00
def __init__(self, api_key: str, api_secret: str, symbols: List[Symbol], tick_duration: int = 1, ):
if api_key is None:
print("API_KEY is not set!")
raise ValueError
if api_secret is None:
print("API_SECRET is not set!")
raise ValueError
2020-11-30 09:12:43 +00:00
self.bfx: BfxWrapper = BfxWrapper(api_key, api_secret)
2020-11-30 14:38:28 +00:00
self.status: Dict[Symbol, SymbolStatus] = {}
2020-11-30 09:12:43 +00:00
self.ticker: Ticker = Ticker(tick_duration)
2020-12-10 16:29:26 +00:00
if isinstance(symbols, Symbol):
symbols = [symbols]
self.symbols: List[Symbol] = symbols
# init symbol statuses
for s in self.symbols:
self.status[s] = SymbolStatus(s)
2020-11-30 09:12:43 +00:00
async def __update_status__(self):
active_positions = await self.bfx.get_active_position()
2020-12-10 16:29:26 +00:00
for symbol in self.status:
# updating tick
self.status[symbol].current_tick = self.ticker.current_tick
# updating last price
last_price = await self.bfx.get_current_prices(symbol)
last_price = last_price[0]
2020-11-30 09:12:43 +00:00
2020-12-10 16:29:26 +00:00
self.status[symbol].set_price(self.ticker.current_tick, last_price)
2020-11-30 14:38:28 +00:00
2020-12-10 16:29:26 +00:00
# updating positions
for p in [x for x in active_positions if x.symbol == symbol]:
await self.status[p.symbol].add_position(p)
2020-11-30 09:12:43 +00:00
2020-12-10 16:29:26 +00:00
# # updating orders
# active_orders = await self.bfx.get_active_orders(symbol)
#
# for o in active_orders:
# self.status[symbol].add_order(o)
2020-11-30 09:12:43 +00:00
2020-12-10 16:29:26 +00:00
# emitting event
await self.status[symbol].__add_event__(Event(EventKind.NEW_TICK, 0, self.ticker.current_tick))
2020-11-30 14:38:28 +00:00
2020-11-30 09:12:43 +00:00
2020-11-30 14:38:28 +00:00
def event_handler(self, symbol) -> EventHandler:
if symbol not in self.status:
return None
return self.status[symbol].eh
def status(self, symbol: Symbol) -> SymbolStatus:
if symbol not in self.status:
return None
return self.status[symbol]
async def start(self):
await self.__update_status__()
2020-11-30 09:12:43 +00:00
async def update(self):
self.ticker.inc()
2020-11-30 14:38:28 +00:00
sleep(self.ticker.seconds)
2020-11-30 09:12:43 +00:00
await self.__update_status__()
2020-11-30 14:38:28 +00:00
def set_strategy(self, symbol, strategy: Strategy):
if symbol in self.status:
self.status[symbol].strategy = strategy
else:
self.status[symbol] = SymbolStatus(symbol, strategy)