From 20f8a75f4a8906641bbb1b198d05cc15148fff02 Mon Sep 17 00:00:00 2001 From: AvishaiW Date: Wed, 21 Feb 2018 20:42:39 +0200 Subject: [PATCH] BUG: for issue #237, update positions before checking balances --- catalyst/exchange/exchange.py | 11 ++++++++--- catalyst/exchange/exchange_algorithm.py | 21 ++++++++++----------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/catalyst/exchange/exchange.py b/catalyst/exchange/exchange.py index c1b64f7c..3b57256b 100644 --- a/catalyst/exchange/exchange.py +++ b/catalyst/exchange/exchange.py @@ -656,16 +656,21 @@ class Exchange: return df - def _check_low_balance(self, currency, balances, amount): + def _check_low_balance(self, currency, balances, amount, open_orders=None): free = balances[currency]['free'] if currency in balances else 0.0 + if open_orders: + # TODO: make sure that this works + free += sum([order.amount for order in open_orders]) + if free < amount: return free, True else: return free, False - def sync_positions(self, positions, cash=None, check_balances=False): + def sync_positions(self, positions, open_orders=None, cash=None, + check_balances=False): """ Update the portfolio cash and position balances based on the latest ticker prices. @@ -694,7 +699,7 @@ class Exchange: balances=balances, amount=cash, ) - if is_lower: + if is_lower and not open_orders: raise NotEnoughCashError( currency=self.base_currency, exchange=self.name, diff --git a/catalyst/exchange/exchange_algorithm.py b/catalyst/exchange/exchange_algorithm.py index 5c9f8771..c827af4a 100644 --- a/catalyst/exchange/exchange_algorithm.py +++ b/catalyst/exchange/exchange_algorithm.py @@ -631,23 +631,12 @@ class ExchangeTradingAlgorithmLive(ExchangeTradingAlgorithmBase): if base_currency is None: base_currency = exchange.base_currency - # Don't check the cash if there are open orders. This could - # results in false positives. orders = [] for asset in self.blotter.open_orders: asset_orders = self.blotter.open_orders[asset] if asset_orders: orders += asset_orders - required_cash = self.portfolio.cash if not orders else None - cash, positions_value = exchange.sync_positions( - positions=exchange_positions, - check_balances=check_balances, - cash=required_cash, - ) - total_cash += cash - total_positions_value += positions_value - # Applying modifications to the original positions for position in exchange_positions: tracker.update_position( @@ -657,6 +646,16 @@ class ExchangeTradingAlgorithmLive(ExchangeTradingAlgorithmBase): last_sale_price=position.last_sale_price, ) + required_cash = self.portfolio.cash if not orders else None + cash, positions_value = exchange.sync_positions( + positions=exchange_positions, + open_orders=orders, + check_balances=check_balances, + cash=required_cash, + ) + total_cash += cash + total_positions_value += positions_value + if not check_balances: total_cash = self.portfolio.cash