restructure _process to eliminate race conditions

This commit is contained in:
gcarq 2017-09-09 15:30:08 +02:00
parent a4b2f4e4b9
commit 52bda0f886

17
main.py
View File

@ -48,14 +48,6 @@ def _process() -> None:
logger.exception('Unable to create trade') logger.exception('Unable to create trade')
for trade in trades: for trade in trades:
if close_trade_if_fulfilled(trade):
logger.info(
'No open orders found and trade is fulfilled. Marking %s as closed ...',
trade
)
Trade.session.flush()
for trade in filter(lambda t: t.is_open, trades):
# Check if there is already an open order for this trade # Check if there is already an open order for this trade
orders = exchange.get_open_orders(trade.pair) orders = exchange.get_open_orders(trade.pair)
orders = [o for o in orders if o['id'] == trade.open_order_id] orders = [o for o in orders if o['id'] == trade.open_order_id]
@ -64,9 +56,11 @@ def _process() -> None:
else: else:
# Update state # Update state
trade.open_order_id = None trade.open_order_id = None
# Check if we can sell our current pair # Check if this trade can be closed
handle_trade(trade) if not close_trade_if_fulfilled(trade):
Trade.session.flush() # Check if we can sell our current pair
handle_trade(trade)
Trade.session.flush()
except (ConnectionError, json.JSONDecodeError) as error: except (ConnectionError, json.JSONDecodeError) as error:
msg = 'Got {} in _process()'.format(error.__class__.__name__) msg = 'Got {} in _process()'.format(error.__class__.__name__)
logger.exception(msg) logger.exception(msg)
@ -85,6 +79,7 @@ def close_trade_if_fulfilled(trade: Trade) -> bool:
and trade.close_rate is not None \ and trade.close_rate is not None \
and trade.open_order_id is None: and trade.open_order_id is None:
trade.is_open = False trade.is_open = False
logger.info('No open orders found and trade is fulfilled. Marking %s as closed ...', trade)
return True return True
return False return False