added positions on connect event. new socketio event, new_event

This commit is contained in:
Giulio De Pasquale 2020-12-16 11:44:12 +00:00
parent ff0796024a
commit 4114333632

30
main.py
View File

@ -13,6 +13,7 @@ from flask_socketio import SocketIO
from bfxbot import BfxBot from bfxbot import BfxBot
from bfxbot.currency import Symbol from bfxbot.currency import Symbol
from bfxbot.models import PositionWrapper, SymbolStatus, Event, EventKind from bfxbot.models import PositionWrapper, SymbolStatus, Event, EventKind
from bfxbot.utils import pos_to_json
from strategy import TrailingStopStrategy from strategy import TrailingStopStrategy
@ -64,18 +65,22 @@ def on_close_position(message: dict):
@socketio.on('connect') @socketio.on('connect')
def on_connect(): def on_connect():
# sleeping on exception to avoid race condition # sleeping on exception to avoid race condition
ticks, prices = [], [] ticks, prices, positions = [], [], []
while not ticks or not prices: while not ticks or not prices:
try: try:
ticks = bot.symbol_status(Symbol.BTC).all_ticks() ticks = bot.symbol_status(Symbol.BTC).all_ticks()
prices = bot.symbol_status(Symbol.BTC).all_prices() prices = bot.symbol_status(Symbol.BTC).all_prices()
positions = bot.symbol_status(Symbol.BTC).current_positions()
except KeyError: except KeyError:
sleep(1) sleep(1)
socketio.emit("first_connect", socketio.emit("first_connect",
{"ticks": ticks, {
"prices": prices}) "ticks": ticks,
"prices": prices,
"positions": list(map(pos_to_json, positions))
})
################################### ###################################
@ -84,18 +89,6 @@ def on_connect():
@btc_eh.on_event(EventKind.NEW_TICK) @btc_eh.on_event(EventKind.NEW_TICK)
def on_new_tick(event: Event, status: SymbolStatus): def on_new_tick(event: Event, status: SymbolStatus):
# TODO: finalize JSON structure
def pos_to_json(pw: PositionWrapper):
return {
"id": pw.position.id,
"amount": pw.position.amount,
"base_price": pw.position.base_price,
"state": str(pw.state()),
"symbol": pw.position.symbol,
"profit_loss": pw.net_profit_loss(),
"profit_loss_percentage": pw.net_profit_loss_percentage()
}
tick = event.tick tick = event.tick
price = status.prices[event.tick] price = status.prices[event.tick]
@ -106,5 +99,12 @@ def on_new_tick(event: Event, status: SymbolStatus):
"positions": list(map(pos_to_json, positions))}) "positions": list(map(pos_to_json, positions))})
@btc_eh.on_any_event()
def on_any_event(event: Event, _):
socketio.emit("new_event", {
"tick": event.tick,
"kind": event.kind.name
})
if __name__ == '__main__': if __name__ == '__main__':
socketio.run(app, debug=True) socketio.run(app, debug=True)