]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/commitdiff
Separate store and add helper
authorIsmaël Bouya <ismael.bouya@normalesup.org>
Sat, 10 Feb 2018 12:52:46 +0000 (13:52 +0100)
committerIsmaël Bouya <ismael.bouya@normalesup.org>
Sat, 10 Feb 2018 14:25:27 +0000 (15:25 +0100)
helper.py [new file with mode: 0644]
portfolio.py
store.py [new file with mode: 0644]
test.py

diff --git a/helper.py b/helper.py
new file mode 100644 (file)
index 0000000..8a29f40
--- /dev/null
+++ b/helper.py
@@ -0,0 +1,151 @@
+import time
+from ccxt import ExchangeError
+from store import *
+
+def move_balances(market, debug=False):
+    needed_in_margin = {} 
+    for trade in TradeStore.all:
+        if trade.trade_type == "short":
+            if trade.value_to.currency not in needed_in_margin:
+                needed_in_margin[trade.value_to.currency] = 0
+            needed_in_margin[trade.value_to.currency] += abs(trade.value_to)
+    for currency, needed in needed_in_margin.items():
+        current_balance = BalanceStore.all[currency].margin_free
+        delta = (needed - current_balance).value
+        # FIXME: don't remove too much if there are open margin position
+        if delta > 0:
+            if debug:
+                print("market.transfer_balance({}, {}, 'exchange', 'margin')".format(currency, delta))
+            else:
+                market.transfer_balance(currency, delta, "exchange", "margin")
+        elif delta < 0:
+            if debug:
+                print("market.transfer_balance({}, {}, 'margin', 'exchange')".format(currency, -delta))
+            else:
+                market.transfer_balance(currency, -delta, "margin", "exchange")
+
+    BalanceStore.fetch_balances(market)
+
+ticker_cache = {}
+ticker_cache_timestamp = time.time()
+def get_ticker(c1, c2, market, refresh=False):
+    global ticker_cache, ticker_cache_timestamp
+    def invert(ticker):
+        return {
+                "inverted": True,
+                "average": (1/ticker["bid"] + 1/ticker["ask"]) / 2,
+                "original": ticker,
+                }
+    def augment_ticker(ticker):
+        ticker.update({
+            "inverted": False,
+            "average": (ticker["bid"] + ticker["ask"] ) / 2,
+            })
+
+    if time.time() - ticker_cache_timestamp > 5:
+        ticker_cache = {}
+        ticker_cache_timestamp = time.time()
+    elif not refresh:
+        if (c1, c2, market.__class__) in ticker_cache:
+            return ticker_cache[(c1, c2, market.__class__)]
+        if (c2, c1, market.__class__) in ticker_cache:
+            return invert(ticker_cache[(c2, c1, market.__class__)])
+
+    try:
+        ticker_cache[(c1, c2, market.__class__)] = market.fetch_ticker("{}/{}".format(c1, c2))
+        augment_ticker(ticker_cache[(c1, c2, market.__class__)])
+    except ExchangeError:
+        try:
+            ticker_cache[(c2, c1, market.__class__)] = market.fetch_ticker("{}/{}".format(c2, c1))
+            augment_ticker(ticker_cache[(c2, c1, market.__class__)])
+        except ExchangeError:
+            ticker_cache[(c1, c2, market.__class__)] = None
+    return get_ticker(c1, c2, market)
+
+fees_cache = {}
+def fetch_fees(market):
+    global fees_cache
+    if market.__class__ not in fees_cache:
+        fees_cache[market.__class__] = market.fetch_fees()
+    return fees_cache[market.__class__]
+
+def prepare_trades(market, base_currency="BTC", compute_value="average", debug=False):
+    BalanceStore.fetch_balances(market)
+    values_in_base = BalanceStore.in_currency(base_currency, market, compute_value=compute_value)
+    total_base_value = sum(values_in_base.values())
+    new_repartition = BalanceStore.dispatch_assets(total_base_value)
+    # Recompute it in case we have new currencies
+    values_in_base = BalanceStore.in_currency(base_currency, market, compute_value=compute_value)
+    TradeStore.compute_trades(values_in_base, new_repartition, market=market, debug=debug)
+
+def update_trades(market, base_currency="BTC", compute_value="average", only=None, debug=False):
+    BalanceStore.fetch_balances(market)
+    values_in_base = BalanceStore.in_currency(base_currency, market, compute_value=compute_value)
+    total_base_value = sum(values_in_base.values())
+    new_repartition = BalanceStore.dispatch_assets(total_base_value)
+    TradeStore.compute_trades(values_in_base, new_repartition, only=only, market=market, debug=debug)
+
+def prepare_trades_to_sell_all(market, base_currency="BTC", compute_value="average", debug=False):
+    BalanceStore.fetch_balances(market)
+    values_in_base = BalanceStore.in_currency(base_currency, market, compute_value=compute_value)
+    total_base_value = sum(values_in_base.values())
+    new_repartition = BalanceStore.dispatch_assets(total_base_value, repartition={ base_currency: (1, "long") })
+    TradeStore.compute_trades(values_in_base, new_repartition, market=market, debug=debug)
+
+def follow_orders(verbose=True, sleep=None):
+    if sleep is None:
+        sleep = 7 if TradeStore.debug else 30
+    tick = 0
+    while len(TradeStore.all_orders(state="open")) > 0:
+        time.sleep(sleep)
+        tick += 1
+        for order in TradeStore.all_orders(state="open"):
+            if order.get_status() != "open":
+                if verbose:
+                    print("finished {}".format(order))
+            else:
+                order.trade.update_order(order, tick)
+    if verbose:
+        print("All orders finished")
+
+def print_orders(market, base_currency="BTC"):
+    prepare_trades(market, base_currency=base_currency, compute_value="average")
+    TradeStore.prepare_orders(compute_value="average")
+    for currency, balance in BalanceStore.all.items():
+        print(balance)
+    TradeStore.print_all_with_order()
+
+def make_orders(market, base_currency="BTC"):
+    prepare_trades(market, base_currency=base_currency)
+    for trade in TradeStore.all:
+        print(trade)
+        for order in trade.orders:
+            print("\t", order, sep="")
+            order.run()
+
+def process_sell_all_sell(market, base_currency="BTC", debug=False):
+    prepare_trades_to_sell_all(market, debug=debug)
+    TradeStore.prepare_orders(compute_value="average")
+    print("------------------")
+    for currency, balance in BalanceStore.all.items():
+        print(balance)
+    print("------------------")
+    TradeStore.print_all_with_order()
+    print("------------------")
+    TradeStore.run_orders()
+    follow_orders()
+
+def process_sell_all_buy(market, base_currency="BTC", debug=False):
+    prepare_trades(market, debug=debug)
+    TradeStore.prepare_orders()
+    print("------------------")
+    for currency, balance in BalanceStore.all.items():
+        print(balance)
+    print("------------------")
+    TradeStore.print_all_with_order()
+    print("------------------")
+    move_balances(market, debug=debug)
+    TradeStore.run_orders()
+    follow_orders()
+
+
index 45fbef98e72fefac5104223955a1b1897f632131..efd9b84e498e20f39f0eb5a7e35d464d2b81614a 100644 (file)
@@ -1,14 +1,13 @@
-from ccxt import ExchangeError
 import time
 from decimal import Decimal as D, ROUND_DOWN
 # Put your poloniex api key in market.py
-from market import market
 from json import JSONDecodeError
 import requests
+import helper as h
+from store import *
 
 # FIXME: correctly handle web call timeouts
 
-
 class Portfolio:
     URL = "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json"
     liquidities = {}
@@ -69,6 +68,24 @@ class Portfolio:
                 "high":   high_liquidity,
                 }
 
+class Computation:
+    computations = {
+            "default": lambda x, y: x[y],
+            "average": lambda x, y: x["average"],
+            "bid": lambda x, y: x["bid"],
+            "ask": lambda x, y: x["ask"],
+            }
+
+    @classmethod
+    def compute_value(cls, ticker, action, compute_value="default"):
+        if action == "buy":
+            action = "ask"
+        if action == "sell":
+            action = "bid"
+        if isinstance(compute_value, str):
+            compute_value = cls.computations[compute_value]
+        return compute_value(ticker, action)
+
 class Amount:
     def __init__(self, currency, value, linked_to=None, ticker=None, rate=None):
         self.currency = currency
@@ -86,9 +103,9 @@ class Amount:
                     self.value * rate,
                     linked_to=self,
                     rate=rate)
-        asset_ticker = Trade.get_ticker(self.currency, other_currency, market)
+        asset_ticker = h.get_ticker(self.currency, other_currency, market)
         if asset_ticker is not None:
-            rate = Trade.compute_value(asset_ticker, action, compute_value=compute_value)
+            rate = Computation.compute_value(asset_ticker, action, compute_value=compute_value)
             return Amount(
                     other_currency,
                     self.value * rate,
@@ -180,7 +197,6 @@ class Amount:
             return "Amount({:.8f} {} -> {})".format(self.value, self.currency, repr(self.linked_to))
 
 class Balance:
-    known_balances = {}
 
     def __init__(self, currency, hash_):
         self.currency = currency
@@ -201,69 +217,6 @@ class Balance:
                     ]:
                 setattr(self, key, Amount(base_currency, hash_.get(key, 0)))
 
-    @classmethod
-    def in_currency(cls, other_currency, market, compute_value="average", type="total"):
-        amounts = {}
-        for currency in cls.known_balances:
-            balance = cls.known_balances[currency]
-            other_currency_amount = getattr(balance, type)\
-                    .in_currency(other_currency, market, compute_value=compute_value)
-            amounts[currency] = other_currency_amount
-        return amounts
-
-    @classmethod
-    def currencies(cls):
-        return cls.known_balances.keys()
-
-    @classmethod
-    def fetch_balances(cls, market):
-        all_balances = market.fetch_all_balances()
-        for currency, balance in all_balances.items():
-            if balance["exchange_total"] != 0 or balance["margin_total"] != 0 or \
-                    currency in cls.known_balances:
-                cls.known_balances[currency] = cls(currency, balance)
-        return cls.known_balances
-
-    @classmethod
-    def dispatch_assets(cls, amount, repartition=None):
-        if repartition is None:
-            repartition = Portfolio.repartition()
-        sum_ratio = sum([v[0] for k, v in repartition.items()])
-        amounts = {}
-        for currency, (ptt, trade_type) in repartition.items():
-            amounts[currency] = ptt * amount / sum_ratio
-            if trade_type == "short":
-                amounts[currency] = - amounts[currency]
-            if currency not in cls.known_balances:
-                cls.known_balances[currency] = cls(currency, {})
-        return amounts
-
-    @classmethod
-    def prepare_trades(cls, market, base_currency="BTC", compute_value="average", debug=False):
-        cls.fetch_balances(market)
-        values_in_base = cls.in_currency(base_currency, market, compute_value=compute_value)
-        total_base_value = sum(values_in_base.values())
-        new_repartition = cls.dispatch_assets(total_base_value)
-        # Recompute it in case we have new currencies
-        values_in_base = cls.in_currency(base_currency, market, compute_value=compute_value)
-        Trade.compute_trades(values_in_base, new_repartition, market=market, debug=debug)
-
-    @classmethod
-    def update_trades(cls, market, base_currency="BTC", compute_value="average", only=None, debug=False):
-        cls.fetch_balances(market)
-        values_in_base = cls.in_currency(base_currency, market, compute_value=compute_value)
-        total_base_value = sum(values_in_base.values())
-        new_repartition = cls.dispatch_assets(total_base_value)
-        Trade.compute_trades(values_in_base, new_repartition, only=only, market=market, debug=debug)
-
-    @classmethod
-    def prepare_trades_to_sell_all(cls, market, base_currency="BTC", compute_value="average", debug=False):
-        cls.fetch_balances(market)
-        values_in_base = cls.in_currency(base_currency, market, compute_value=compute_value)
-        total_base_value = sum(values_in_base.values())
-        new_repartition = cls.dispatch_assets(total_base_value, repartition={ base_currency: (1, "long") })
-        Trade.compute_trades(values_in_base, new_repartition, market=market, debug=debug)
-
     def __repr__(self):
         if self.exchange_total > 0:
             if self.exchange_free > 0 and self.exchange_used > 0:
@@ -296,18 +249,7 @@ class Balance:
 
         return "Balance({}".format(self.currency) + "".join([exchange, margin, total]) + ")"
 
-class Computation:
-    computations = {
-            "default": lambda x, y: x[y],
-            "average": lambda x, y: x["average"],
-            "bid": lambda x, y: x["bid"],
-            "ask": lambda x, y: x["ask"],
-            }
-
 class Trade:
-    debug = False
-    trades = []
-
     def __init__(self, value_from, value_to, currency, market=None):
         # We have value_from of currency, and want to finish with value_to of
         # that currency. value_* may not be in currency's terms
@@ -323,105 +265,6 @@ class Trade:
             self.value_from.linked_to = Amount(self.currency, 0)
         self.base_currency = self.value_from.currency
 
-    fees_cache = {}
-    @classmethod
-    def fetch_fees(cls, market):
-        if market.__class__ not in cls.fees_cache:
-            cls.fees_cache[market.__class__] = market.fetch_fees()
-        return cls.fees_cache[market.__class__]
-
-    ticker_cache = {}
-    ticker_cache_timestamp = time.time()
-    @classmethod
-    def get_ticker(cls, c1, c2, market, refresh=False):
-        def invert(ticker):
-            return {
-                    "inverted": True,
-                    "average": (1/ticker["bid"] + 1/ticker["ask"]) / 2,
-                    "original": ticker,
-                    }
-        def augment_ticker(ticker):
-            ticker.update({
-                "inverted": False,
-                "average": (ticker["bid"] + ticker["ask"] ) / 2,
-                })
-
-        if time.time() - cls.ticker_cache_timestamp > 5:
-            cls.ticker_cache = {}
-            cls.ticker_cache_timestamp = time.time()
-        elif not refresh:
-            if (c1, c2, market.__class__) in cls.ticker_cache:
-                return cls.ticker_cache[(c1, c2, market.__class__)]
-            if (c2, c1, market.__class__) in cls.ticker_cache:
-                return invert(cls.ticker_cache[(c2, c1, market.__class__)])
-
-        try:
-            cls.ticker_cache[(c1, c2, market.__class__)] = market.fetch_ticker("{}/{}".format(c1, c2))
-            augment_ticker(cls.ticker_cache[(c1, c2, market.__class__)])
-        except ExchangeError:
-            try:
-                cls.ticker_cache[(c2, c1, market.__class__)] = market.fetch_ticker("{}/{}".format(c2, c1))
-                augment_ticker(cls.ticker_cache[(c2, c1, market.__class__)])
-            except ExchangeError:
-                cls.ticker_cache[(c1, c2, market.__class__)] = None
-        return cls.get_ticker(c1, c2, market)
-
-    @classmethod
-    def compute_trades(cls, values_in_base, new_repartition, only=None, market=None, debug=False):
-        cls.debug = cls.debug or debug
-        base_currency = sum(values_in_base.values()).currency
-        for currency in Balance.currencies():
-            if currency == base_currency:
-                continue
-            value_from = values_in_base.get(currency, Amount(base_currency, 0))
-            value_to = new_repartition.get(currency, Amount(base_currency, 0))
-            if value_from.value * value_to.value < 0:
-                trade_1 = cls(value_from, Amount(base_currency, 0), currency, market=market)
-                if only is None or trade_1.action == only:
-                    cls.trades.append(trade_1)
-                trade_2 = cls(Amount(base_currency, 0), value_to, currency, market=market)
-                if only is None or trade_2.action == only:
-                    cls.trades.append(trade_2)
-            else:
-                trade = cls(
-                    value_from,
-                    value_to,
-                    currency,
-                    market=market
-                    )
-                if only is None or trade.action == only:
-                    cls.trades.append(trade)
-        return cls.trades
-
-    @classmethod
-    def prepare_orders(cls, only=None, compute_value="default"):
-        for trade in cls.trades:
-            if only is None or trade.action == only:
-                trade.prepare_order(compute_value=compute_value)
-
-    @classmethod
-    def move_balances(cls, market):
-        needed_in_margin = {} 
-        for trade in cls.trades:
-            if trade.trade_type == "short":
-                if trade.value_to.currency not in needed_in_margin:
-                    needed_in_margin[trade.value_to.currency] = 0
-                needed_in_margin[trade.value_to.currency] += abs(trade.value_to)
-        for currency, needed in needed_in_margin.items():
-            current_balance = Balance.known_balances[currency].margin_free
-            delta = (needed - current_balance).value
-            # FIXME: don't remove too much if there are open margin position
-            if delta > 0:
-                if cls.debug:
-                    print("market.transfer_balance({}, {}, 'exchange', 'margin')".format(currency, delta))
-                else:
-                    market.transfer_balance(currency, delta, "exchange", "margin")
-            elif delta < 0:
-                if cls.debug:
-                    print("market.transfer_balance({}, {}, 'margin', 'exchange')".format(currency, -delta))
-                else:
-                    market.transfer_balance(currency, -delta, "margin", "exchange")
-
     @property
     def action(self):
         if self.value_from == self.value_to:
@@ -481,11 +324,11 @@ class Trade:
     def prepare_order(self, compute_value="default"):
         if self.action is None:
             return
-        ticker = Trade.get_ticker(self.currency, self.base_currency, self.market)
+        ticker = h.get_ticker(self.currency, self.base_currency, self.market)
         inverted = ticker["inverted"]
         if inverted:
             ticker = ticker["original"]
-        rate = Trade.compute_value(ticker, self.order_action(inverted), compute_value=compute_value)
+        rate = Computation.compute_value(ticker, self.order_action(inverted), compute_value=compute_value)
         # 0.1
 
         delta_in_base = abs(self.value_from - self.value_to)
@@ -536,51 +379,6 @@ class Trade:
             delta - self.filled_amount, rate, currency, self.trade_type,
             self.market, self, close_if_possible=close_if_possible))
 
-    @classmethod
-    def compute_value(cls, ticker, action, compute_value="default"):
-        if action == "buy":
-            action = "ask"
-        if action == "sell":
-            action = "bid"
-        if isinstance(compute_value, str):
-            compute_value = Computation.computations[compute_value]
-        return compute_value(ticker, action)
-
-    @classmethod
-    def all_orders(cls, state=None):
-        all_orders = sum(map(lambda v: v.orders, cls.trades), [])
-        if state is None:
-            return all_orders
-        else:
-            return list(filter(lambda o: o.status == state, all_orders))
-
-    @classmethod
-    def run_orders(cls):
-        for order in cls.all_orders(state="pending"):
-            order.run()
-
-    @classmethod
-    def follow_orders(cls, verbose=True, sleep=None):
-        if sleep is None:
-            sleep = 7 if cls.debug else 30
-        tick = 0
-        while len(cls.all_orders(state="open")) > 0:
-            time.sleep(sleep)
-            tick += 1
-            for order in cls.all_orders(state="open"):
-                if order.get_status() != "open":
-                    if verbose:
-                        print("finished {}".format(order))
-                else:
-                    order.trade.update_order(order, tick)
-        if verbose:
-            print("All orders finished")
-
-    @classmethod
-    def update_all_orders_status(cls):
-        for order in cls.all_orders(state="open"):
-            order.get_status()
-
     def __repr__(self):
         return "Trade({} -> {} in {}, {})".format(
                 self.value_from,
@@ -588,11 +386,6 @@ class Trade:
                 self.currency,
                 self.action)
 
-    @classmethod
-    def print_all_with_order(cls):
-        for trade in cls.trades:
-            trade.print_with_order()
-
     def print_with_order(self):
         print(self)
         for order in self.orders:
@@ -612,7 +405,6 @@ class Order:
         self.status = "pending"
         self.trade = trade
         self.close_if_possible = close_if_possible
-        self.debug = trade.debug
 
     def __repr__(self):
         return "Order({} {} {} at {} {} [{}]{})".format(
@@ -648,7 +440,7 @@ class Order:
         symbol = "{}/{}".format(self.amount.currency, self.base_currency)
         amount = round(self.amount, self.market.order_precision(symbol)).value
 
-        if self.debug:
+        if TradeStore.debug:
             print("market.create_order('{}', 'limit', '{}', {}, price={}, account={})".format(
                 symbol, self.action, amount, self.rate, self.account))
             self.status = "open"
@@ -665,7 +457,7 @@ class Order:
                 print(self.error_message)
 
     def get_status(self):
-        if self.debug:
+        if TradeStore.debug:
             return self.status
         # other states are "closed" and "canceled"
         if self.status == "open":
@@ -675,7 +467,7 @@ class Order:
         return self.status
 
     def mark_finished_order(self):
-        if self.debug:
+        if TradeStore.debug:
             return
         if self.status == "closed":
             if self.trade_type == "short" and self.action == "buy" and self.close_if_possible:
@@ -683,7 +475,7 @@ class Order:
 
     fetch_cache_timestamp = None
     def fetch(self, force=False):
-        if self.debug or (not force and self.fetch_cache_timestamp is not None
+        if TradeStore.debug or (not force and self.fetch_cache_timestamp is not None
                 and time.time() - self.fetch_cache_timestamp < 10):
             return
         self.fetch_cache_timestamp = time.time()
@@ -725,7 +517,7 @@ class Order:
                 self.base_currency, mouvement_hash))
 
     def cancel(self):
-        if self.debug:
+        if TradeStore.debug:
             self.status = "canceled"
             return
         self.market.cancel_order(self.result['id'])
@@ -744,45 +536,6 @@ class Mouvement:
         # rate * total = total_in_base
         self.total_in_base = Amount(base_currency, hash_["total"])
 
-def print_orders(market, base_currency="BTC"):
-    Balance.prepare_trades(market, base_currency=base_currency, compute_value="average")
-    Trade.prepare_orders(compute_value="average")
-    for currency, balance in Balance.known_balances.items():
-        print(balance)
-    Trade.print_all_with_order()
-
-def make_orders(market, base_currency="BTC"):
-    Balance.prepare_trades(market, base_currency=base_currency)
-    for trade in Trade.trades:
-        print(trade)
-        for order in trade.orders:
-            print("\t", order, sep="")
-            order.run()
-
-def process_sell_all_sell(market, base_currency="BTC", debug=False):
-    Balance.prepare_trades_to_sell_all(market, debug=debug)
-    Trade.prepare_orders(compute_value="average")
-    print("------------------")
-    for currency, balance in Balance.known_balances.items():
-        print(balance)
-    print("------------------")
-    Trade.print_all_with_order()
-    print("------------------")
-    Trade.run_orders()
-    Trade.follow_orders()
-
-def process_sell_all_buy(market, base_currency="BTC", debug=False):
-    Balance.prepare_trades(market, debug=debug)
-    Trade.prepare_orders()
-    print("------------------")
-    for currency, balance in Balance.known_balances.items():
-        print(balance)
-    print("------------------")
-    Trade.print_all_with_order()
-    print("------------------")
-    Trade.move_balances(market)
-    Trade.run_orders()
-    Trade.follow_orders()
-
 if __name__ == '__main__':
-    print_orders(market)
+    from market import market
+    h.print_orders(market)
diff --git a/store.py b/store.py
new file mode 100644 (file)
index 0000000..4e46878
--- /dev/null
+++ b/store.py
@@ -0,0 +1,102 @@
+import portfolio
+
+__all__ = ["BalanceStore", "TradeStore"]
+
+class BalanceStore:
+    all = {}
+
+    @classmethod
+    def currencies(cls):
+        return cls.all.keys()
+
+    @classmethod
+    def in_currency(cls, other_currency, market, compute_value="average", type="total"):
+        amounts = {}
+        for currency, balance in cls.all.items():
+            other_currency_amount = getattr(balance, type)\
+                    .in_currency(other_currency, market, compute_value=compute_value)
+            amounts[currency] = other_currency_amount
+        return amounts
+
+    @classmethod
+    def fetch_balances(cls, market):
+        all_balances = market.fetch_all_balances()
+        for currency, balance in all_balances.items():
+            if balance["exchange_total"] != 0 or balance["margin_total"] != 0 or \
+                    currency in cls.all:
+                cls.all[currency] = portfolio.Balance(currency, balance)
+
+    @classmethod
+    def dispatch_assets(cls, amount, repartition=None):
+        if repartition is None:
+            repartition = portfolio.Portfolio.repartition()
+        sum_ratio = sum([v[0] for k, v in repartition.items()])
+        amounts = {}
+        for currency, (ptt, trade_type) in repartition.items():
+            amounts[currency] = ptt * amount / sum_ratio
+            if trade_type == "short":
+                amounts[currency] = - amounts[currency]
+            if currency not in BalanceStore.all:
+                cls.all[currency] = portfolio.Balance(currency, {})
+        return amounts
+
+class TradeStore:
+    all = []
+    debug = False
+
+    @classmethod
+    def compute_trades(cls, values_in_base, new_repartition, only=None, market=None, debug=False):
+        cls.debug = cls.debug or debug
+        base_currency = sum(values_in_base.values()).currency
+        for currency in BalanceStore.currencies():
+            if currency == base_currency:
+                continue
+            value_from = values_in_base.get(currency, portfolio.Amount(base_currency, 0))
+            value_to = new_repartition.get(currency, portfolio.Amount(base_currency, 0))
+            if value_from.value * value_to.value < 0:
+                trade_1 = portfolio.Trade(value_from, portfolio.Amount(base_currency, 0), currency, market=market)
+                if only is None or trade_1.action == only:
+                    cls.all.append(trade_1)
+                trade_2 = portfolio.Trade(portfolio.Amount(base_currency, 0), value_to, currency, market=market)
+                if only is None or trade_2.action == only:
+                    cls.all.append(trade_2)
+            else:
+                trade = portfolio.Trade(
+                    value_from,
+                    value_to,
+                    currency,
+                    market=market
+                    )
+                if only is None or trade.action == only:
+                    cls.all.append(trade)
+
+    @classmethod
+    def prepare_orders(cls, only=None, compute_value="default"):
+        for trade in cls.all:
+            if only is None or trade.action == only:
+                trade.prepare_order(compute_value=compute_value)
+
+    @classmethod
+    def print_all_with_order(cls):
+        for trade in cls.all:
+            trade.print_with_order()
+
+    @classmethod
+    def run_orders(cls):
+        for order in cls.all_orders(state="pending"):
+            order.run()
+
+    @classmethod
+    def all_orders(cls, state=None):
+        all_orders = sum(map(lambda v: v.orders, cls.all), [])
+        if state is None:
+            return all_orders
+        else:
+            return list(filter(lambda o: o.status == state, all_orders))
+
+    @classmethod
+    def update_all_orders_status(cls):
+        for order in cls.all_orders(state="open"):
+            order.get_status()
+
+
diff --git a/test.py b/test.py
index b27eb74f985899d1ce0520715aeb376a21effaf7..aae1dc85af02245f88ddd28d32a4fac9ecfe1cef 100644 (file)
--- a/test.py
+++ b/test.py
@@ -5,6 +5,7 @@ from unittest import mock
 import requests
 import requests_mock
 from io import StringIO
+import helper
 
 class WebMockTestCase(unittest.TestCase):
     import time
@@ -15,16 +16,18 @@ class WebMockTestCase(unittest.TestCase):
         self.wm.start()
 
         self.patchers = [
-                mock.patch.multiple(portfolio.Balance, known_balances={}),
+                mock.patch.multiple(portfolio.BalanceStore,
+                    all={},),
+                mock.patch.multiple(portfolio.TradeStore,
+                    all=[],
+                    debug=False),
                 mock.patch.multiple(portfolio.Portfolio, data=None, liquidities={}),
-                mock.patch.multiple(portfolio.Trade,
-                    ticker_cache={},
-                    ticker_cache_timestamp=self.time.time(),
-                    fees_cache={},
-                    debug=False,
-                    trades=[]),
                 mock.patch.multiple(portfolio.Computation,
-                    computations=portfolio.Computation.computations)
+                    computations=portfolio.Computation.computations),
+                mock.patch.multiple(helper,
+                    fees_cache={},
+                    ticker_cache={},
+                    ticker_cache_timestamp=self.time.time()),
                 ]
         for patcher in self.patchers:
             patcher.start()
@@ -149,12 +152,12 @@ class AmountTest(WebMockTestCase):
         self.assertEqual(amount, amount.in_currency("ETC", None))
 
         ticker_mock = unittest.mock.Mock()
-        with mock.patch.object(portfolio.Trade, 'get_ticker', new=ticker_mock):
+        with mock.patch.object(helper, 'get_ticker', new=ticker_mock):
             ticker_mock.return_value = None
 
             self.assertRaises(Exception, amount.in_currency, "ETH", None)
 
-        with mock.patch.object(portfolio.Trade, 'get_ticker', new=ticker_mock):
+        with mock.patch.object(helper, 'get_ticker', new=ticker_mock):
             ticker_mock.return_value = {
                     "bid": D("0.2"),
                     "ask": D("0.4"),
@@ -361,37 +364,6 @@ class AmountTest(WebMockTestCase):
         self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1))
 
 class BalanceTest(WebMockTestCase):
-    def setUp(self):
-        super(BalanceTest, self).setUp()
-
-        self.fetch_balance = {
-                "ETC": {
-                    "exchange_free": 0,
-                    "exchange_used": 0,
-                    "exchange_total": 0,
-                    "margin_total": 0,
-                    },
-                "USDT": {
-                    "exchange_free": D("6.0"),
-                    "exchange_used": D("1.2"),
-                    "exchange_total": D("7.2"),
-                    "margin_total": 0,
-                    },
-                "XVG": {
-                    "exchange_free": 16,
-                    "exchange_used": 0,
-                    "exchange_total": 16,
-                    "margin_total": 0,
-                    },
-                "XMR": {
-                    "exchange_free": 0,
-                    "exchange_used": 0,
-                    "exchange_total": 0,
-                    "margin_total": D("-1.0"),
-                    "margin_free": 0,
-                    },
-                }
-
     def test_values(self):
         balance = portfolio.Balance("BTC", {
             "exchange_total": "0.65",
@@ -426,91 +398,100 @@ class BalanceTest(WebMockTestCase):
         self.assertEqual(portfolio.D("0.4"), balance.margin_lending_fees.value)
         self.assertEqual("USDT", balance.margin_lending_fees.currency)
 
-    @mock.patch.object(portfolio.Trade, "get_ticker")
-    def test_in_currency(self, get_ticker):
-        portfolio.Balance.known_balances = {
-                "BTC": portfolio.Balance("BTC", {
-                    "total": "0.65",
-                    "exchange_total":"0.65",
-                    "exchange_free": "0.35",
-                    "exchange_used": "0.30"}),
-                "ETH": portfolio.Balance("ETH", {
-                    "total": 3,
-                    "exchange_total": 3,
-                    "exchange_free": 3,
-                    "exchange_used": 0}),
-                }
-        market = mock.Mock()
-        get_ticker.return_value = {
-                "bid": D("0.09"),
-                "ask": D("0.11"),
-                "average": D("0.1"),
-                }
+    def test__repr(self):
+        self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])",
+                repr(portfolio.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 })))
+        balance = portfolio.Balance("BTX", { "exchange_total": 3,
+            "exchange_used": 1, "exchange_free": 2 })
+        self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance))
 
-        amounts = portfolio.Balance.in_currency("BTC", market)
-        self.assertEqual("BTC", amounts["ETH"].currency)
-        self.assertEqual(D("0.65"), amounts["BTC"].value)
-        self.assertEqual(D("0.30"), amounts["ETH"].value)
+        balance = portfolio.Balance("BTX", { "margin_total": 3,
+            "margin_borrowed": 1, "margin_free": 2 })
+        self.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + borrowed 1.00000000 BTX = 3.00000000 BTX])", repr(balance))
 
-        amounts = portfolio.Balance.in_currency("BTC", market, compute_value="bid")
-        self.assertEqual(D("0.65"), amounts["BTC"].value)
-        self.assertEqual(D("0.27"), amounts["ETH"].value)
+        balance = portfolio.Balance("BTX", { "margin_total": -3,
+            "margin_borrowed_base_price": D("0.1"),
+            "margin_borrowed_base_currency": "BTC",
+            "margin_lending_fees": D("0.002") })
+        self.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance))
 
-        amounts = portfolio.Balance.in_currency("BTC", market, compute_value="bid", type="exchange_used")
-        self.assertEqual(D("0.30"), amounts["BTC"].value)
-        self.assertEqual(0, amounts["ETH"].value)
+class HelperTest(WebMockTestCase):
+    def test_get_ticker(self):
+        market = mock.Mock()
+        market.fetch_ticker.side_effect = [
+                { "bid": 1, "ask": 3 },
+                helper.ExchangeError("foo"),
+                { "bid": 10, "ask": 40 },
+                helper.ExchangeError("foo"),
+                helper.ExchangeError("foo"),
+                ]
 
-    def test_currencies(self):
-        portfolio.Balance.known_balances = {
-                "BTC": portfolio.Balance("BTC", {
-                    "total": "0.65",
-                    "exchange_total":"0.65",
-                    "exchange_free": "0.35",
-                    "exchange_used": "0.30"}),
-                "ETH": portfolio.Balance("ETH", {
-                    "total": 3,
-                    "exchange_total": 3,
-                    "exchange_free": 3,
-                    "exchange_used": 0}),
-                }
-        self.assertListEqual(["BTC", "ETH"], list(portfolio.Balance.currencies()))
+        ticker = helper.get_ticker("ETH", "ETC", market)
+        market.fetch_ticker.assert_called_with("ETH/ETC")
+        self.assertEqual(1, ticker["bid"])
+        self.assertEqual(3, ticker["ask"])
+        self.assertEqual(2, ticker["average"])
+        self.assertFalse(ticker["inverted"])
 
-    @mock.patch.object(portfolio.market, "fetch_all_balances")
-    def test_fetch_balances(self, fetch_all_balances):
-        fetch_all_balances.return_value = self.fetch_balance
+        ticker = helper.get_ticker("ETH", "XVG", market)
+        self.assertEqual(0.0625, ticker["average"])
+        self.assertTrue(ticker["inverted"])
+        self.assertIn("original", ticker)
+        self.assertEqual(10, ticker["original"]["bid"])
 
-        portfolio.Balance.fetch_balances(portfolio.market)
-        self.assertNotIn("ETC", portfolio.Balance.currencies())
-        self.assertListEqual(["USDT", "XVG", "XMR"], list(portfolio.Balance.currencies()))
+        ticker = helper.get_ticker("XVG", "XMR", market)
+        self.assertIsNone(ticker)
 
-        portfolio.Balance.known_balances["ETC"] = portfolio.Balance("ETC", {
-            "exchange_total": "1", "exchange_free": "0",
-            "exchange_used": "1" })
-        portfolio.Balance.fetch_balances(portfolio.market)
-        self.assertEqual(0, portfolio.Balance.known_balances["ETC"].total)
-        self.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(portfolio.Balance.currencies()))
+        market.fetch_ticker.assert_has_calls([
+            mock.call("ETH/ETC"),
+            mock.call("ETH/XVG"),
+            mock.call("XVG/ETH"),
+            mock.call("XVG/XMR"),
+            mock.call("XMR/XVG"),
+            ])
 
-    @mock.patch.object(portfolio.Portfolio, "repartition")
-    @mock.patch.object(portfolio.market, "fetch_all_balances")
-    def test_dispatch_assets(self, fetch_all_balances, repartition):
-        fetch_all_balances.return_value = self.fetch_balance
-        portfolio.Balance.fetch_balances(portfolio.market)
+        market2 = mock.Mock()
+        market2.fetch_ticker.side_effect = [
+                { "bid": 1, "ask": 3 },
+                { "bid": 1.2, "ask": 3.5 },
+                ]
+        ticker1 = helper.get_ticker("ETH", "ETC", market2)
+        ticker2 = helper.get_ticker("ETH", "ETC", market2)
+        ticker3 = helper.get_ticker("ETC", "ETH", market2)
+        market2.fetch_ticker.assert_called_once_with("ETH/ETC")
+        self.assertEqual(1, ticker1["bid"])
+        self.assertDictEqual(ticker1, ticker2)
+        self.assertDictEqual(ticker1, ticker3["original"])
 
-        self.assertNotIn("XEM", portfolio.Balance.currencies())
+        ticker4 = helper.get_ticker("ETH", "ETC", market2, refresh=True)
+        ticker5 = helper.get_ticker("ETH", "ETC", market2)
+        self.assertEqual(1.2, ticker4["bid"])
+        self.assertDictEqual(ticker4, ticker5)
 
-        repartition.return_value = {
-                "XEM": (D("0.75"), "long"),
-                "BTC": (D("0.26"), "long"),
-                }
+        market3 = mock.Mock()
+        market3.fetch_ticker.side_effect = [
+                { "bid": 1, "ask": 3 },
+                { "bid": 1.2, "ask": 3.5 },
+                ]
+        ticker6 = helper.get_ticker("ETH", "ETC", market3)
+        helper.ticker_cache_timestamp -= 4
+        ticker7 = helper.get_ticker("ETH", "ETC", market3)
+        helper.ticker_cache_timestamp -= 2
+        ticker8 = helper.get_ticker("ETH", "ETC", market3)
+        self.assertDictEqual(ticker6, ticker7)
+        self.assertEqual(1.2, ticker8["bid"])
 
-        amounts = portfolio.Balance.dispatch_assets(portfolio.Amount("BTC", "10.1"))
-        self.assertIn("XEM", portfolio.Balance.currencies())
-        self.assertEqual(D("2.6"), amounts["BTC"].value)
-        self.assertEqual(D("7.5"), amounts["XEM"].value)
+    def test_fetch_fees(self):
+        market = mock.Mock()
+        market.fetch_fees.return_value = "Foo"
+        self.assertEqual("Foo", helper.fetch_fees(market))
+        market.fetch_fees.assert_called_once()
+        self.assertEqual("Foo", helper.fetch_fees(market))
+        market.fetch_fees.assert_called_once()
 
     @mock.patch.object(portfolio.Portfolio, "repartition")
-    @mock.patch.object(portfolio.Trade, "get_ticker")
-    @mock.patch.object(portfolio.Trade, "compute_trades")
+    @mock.patch.object(helper, "get_ticker")
+    @mock.patch.object(portfolio.TradeStore, "compute_trades")
     def test_prepare_trades(self, compute_trades, get_ticker, repartition):
         repartition.return_value = {
                 "XEM": (D("0.75"), "long"),
@@ -541,7 +522,7 @@ class BalanceTest(WebMockTestCase):
                     "total": D("10000.0")
                     },
                 }
-        portfolio.Balance.prepare_trades(market)
+        helper.prepare_trades(market)
         compute_trades.assert_called()
 
         call = compute_trades.call_args
@@ -552,8 +533,8 @@ class BalanceTest(WebMockTestCase):
         self.assertEqual(D("0.7575"), call[0][1]["XEM"].value)
 
     @mock.patch.object(portfolio.Portfolio, "repartition")
-    @mock.patch.object(portfolio.Trade, "get_ticker")
-    @mock.patch.object(portfolio.Trade, "compute_trades")
+    @mock.patch.object(helper, "get_ticker")
+    @mock.patch.object(portfolio.TradeStore, "compute_trades")
     def test_update_trades(self, compute_trades, get_ticker, repartition):
         repartition.return_value = {
                 "XEM": (D("0.75"), "long"),
@@ -584,7 +565,7 @@ class BalanceTest(WebMockTestCase):
                     "total": D("10000.0")
                     },
                 }
-        portfolio.Balance.update_trades(market)
+        helper.update_trades(market)
         compute_trades.assert_called()
 
         call = compute_trades.call_args
@@ -595,8 +576,8 @@ class BalanceTest(WebMockTestCase):
         self.assertEqual(D("0.7575"), call[0][1]["XEM"].value)
 
     @mock.patch.object(portfolio.Portfolio, "repartition")
-    @mock.patch.object(portfolio.Trade, "get_ticker")
-    @mock.patch.object(portfolio.Trade, "compute_trades")
+    @mock.patch.object(helper, "get_ticker")
+    @mock.patch.object(portfolio.TradeStore, "compute_trades")
     def test_prepare_trades_to_sell_all(self, compute_trades, get_ticker, repartition):
         def _get_ticker(c1, c2, market):
             if c1 == "USDT" and c2 == "BTC":
@@ -621,7 +602,7 @@ class BalanceTest(WebMockTestCase):
                     "total": D("10000.0")
                     },
                 }
-        portfolio.Balance.prepare_trades_to_sell_all(market)
+        helper.prepare_trades_to_sell_all(market)
         repartition.assert_not_called()
         compute_trades.assert_called()
 
@@ -631,89 +612,243 @@ class BalanceTest(WebMockTestCase):
         self.assertEqual(D("0.01"), call[0][0]["XVG"].value)
         self.assertEqual(D("1.01"), call[0][1]["BTC"].value)
 
-    def test__repr(self):
-        self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])",
-                repr(portfolio.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 })))
-        balance = portfolio.Balance("BTX", { "exchange_total": 3,
-            "exchange_used": 1, "exchange_free": 2 })
-        self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance))
+    @unittest.skip("TODO")
+    def test_follow_orders(self):
+        pass
 
-        balance = portfolio.Balance("BTX", { "margin_total": 3,
-            "margin_borrowed": 1, "margin_free": 2 })
-        self.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + borrowed 1.00000000 BTX = 3.00000000 BTX])", repr(balance))
 
-        balance = portfolio.Balance("BTX", { "margin_total": -3,
-            "margin_borrowed_base_price": D("0.1"),
-            "margin_borrowed_base_currency": "BTC",
-            "margin_lending_fees": D("0.002") })
-        self.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance))
+class TradeStoreTest(WebMockTestCase):
+    @unittest.skip("TODO")
+    def test_compute_trades(self):
+        pass
 
-class TradeTest(WebMockTestCase):
+    def test_prepare_orders(self):
+        trade_mock1 = mock.Mock()
+        trade_mock2 = mock.Mock()
 
-    def test_get_ticker(self):
+        portfolio.TradeStore.all.append(trade_mock1)
+        portfolio.TradeStore.all.append(trade_mock2)
+
+        portfolio.TradeStore.prepare_orders()
+        trade_mock1.prepare_order.assert_called_with(compute_value="default")
+        trade_mock2.prepare_order.assert_called_with(compute_value="default")
+
+        portfolio.TradeStore.prepare_orders(compute_value="bla")
+        trade_mock1.prepare_order.assert_called_with(compute_value="bla")
+        trade_mock2.prepare_order.assert_called_with(compute_value="bla")
+
+        trade_mock1.prepare_order.reset_mock()
+        trade_mock2.prepare_order.reset_mock()
+
+        trade_mock1.action = "foo"
+        trade_mock2.action = "bar"
+        portfolio.TradeStore.prepare_orders(only="bar")
+        trade_mock1.prepare_order.assert_not_called()
+        trade_mock2.prepare_order.assert_called_with(compute_value="default")
+
+    def test_print_all_with_order(self):
+        trade_mock1 = mock.Mock()
+        trade_mock2 = mock.Mock()
+        trade_mock3 = mock.Mock()
+        portfolio.TradeStore.all = [trade_mock1, trade_mock2, trade_mock3]
+
+        portfolio.TradeStore.print_all_with_order()
+
+        trade_mock1.print_with_order.assert_called()
+        trade_mock2.print_with_order.assert_called()
+        trade_mock3.print_with_order.assert_called()
+
+    @mock.patch.object(portfolio.TradeStore, "all_orders")
+    def test_run_orders(self, all_orders):
+        order_mock1 = mock.Mock()
+        order_mock2 = mock.Mock()
+        order_mock3 = mock.Mock()
+        all_orders.return_value = [order_mock1, order_mock2, order_mock3]
+        portfolio.TradeStore.run_orders()
+        all_orders.assert_called_with(state="pending")
+
+        order_mock1.run.assert_called()
+        order_mock2.run.assert_called()
+        order_mock3.run.assert_called()
+
+    def test_all_orders(self):
+        trade_mock1 = mock.Mock()
+        trade_mock2 = mock.Mock()
+
+        order_mock1 = mock.Mock()
+        order_mock2 = mock.Mock()
+        order_mock3 = mock.Mock()
+
+        trade_mock1.orders = [order_mock1, order_mock2]
+        trade_mock2.orders = [order_mock3]
+
+        order_mock1.status = "pending"
+        order_mock2.status = "open"
+        order_mock3.status = "open"
+
+        portfolio.TradeStore.all.append(trade_mock1)
+        portfolio.TradeStore.all.append(trade_mock2)
+
+        orders = portfolio.TradeStore.all_orders()
+        self.assertEqual(3, len(orders))
+
+        open_orders = portfolio.TradeStore.all_orders(state="open")
+        self.assertEqual(2, len(open_orders))
+        self.assertEqual([order_mock2, order_mock3], open_orders)
+
+    @mock.patch.object(portfolio.TradeStore, "all_orders")
+    def test_update_all_orders_status(self, all_orders):
+        order_mock1 = mock.Mock()
+        order_mock2 = mock.Mock()
+        order_mock3 = mock.Mock()
+        all_orders.return_value = [order_mock1, order_mock2, order_mock3]
+        portfolio.TradeStore.update_all_orders_status()
+        all_orders.assert_called_with(state="open")
+
+        order_mock1.get_status.assert_called()
+        order_mock2.get_status.assert_called()
+        order_mock3.get_status.assert_called()
+
+
+class BalanceStoreTest(WebMockTestCase):
+    def setUp(self):
+        super(BalanceStoreTest, self).setUp()
+
+        self.fetch_balance = {
+                "ETC": {
+                    "exchange_free": 0,
+                    "exchange_used": 0,
+                    "exchange_total": 0,
+                    "margin_total": 0,
+                    },
+                "USDT": {
+                    "exchange_free": D("6.0"),
+                    "exchange_used": D("1.2"),
+                    "exchange_total": D("7.2"),
+                    "margin_total": 0,
+                    },
+                "XVG": {
+                    "exchange_free": 16,
+                    "exchange_used": 0,
+                    "exchange_total": 16,
+                    "margin_total": 0,
+                    },
+                "XMR": {
+                    "exchange_free": 0,
+                    "exchange_used": 0,
+                    "exchange_total": 0,
+                    "margin_total": D("-1.0"),
+                    "margin_free": 0,
+                    },
+                }
+
+    @mock.patch.object(helper, "get_ticker")
+    def test_in_currency(self, get_ticker):
+        portfolio.BalanceStore.all = {
+                "BTC": portfolio.Balance("BTC", {
+                    "total": "0.65",
+                    "exchange_total":"0.65",
+                    "exchange_free": "0.35",
+                    "exchange_used": "0.30"}),
+                "ETH": portfolio.Balance("ETH", {
+                    "total": 3,
+                    "exchange_total": 3,
+                    "exchange_free": 3,
+                    "exchange_used": 0}),
+                }
         market = mock.Mock()
-        market.fetch_ticker.side_effect = [
-                { "bid": 1, "ask": 3 },
-                portfolio.ExchangeError("foo"),
-                { "bid": 10, "ask": 40 },
-                portfolio.ExchangeError("foo"),
-                portfolio.ExchangeError("foo"),
-                ]
+        get_ticker.return_value = {
+                "bid": D("0.09"),
+                "ask": D("0.11"),
+                "average": D("0.1"),
+                }
 
-        ticker = portfolio.Trade.get_ticker("ETH", "ETC", market)
-        market.fetch_ticker.assert_called_with("ETH/ETC")
-        self.assertEqual(1, ticker["bid"])
-        self.assertEqual(3, ticker["ask"])
-        self.assertEqual(2, ticker["average"])
-        self.assertFalse(ticker["inverted"])
+        amounts = portfolio.BalanceStore.in_currency("BTC", market)
+        self.assertEqual("BTC", amounts["ETH"].currency)
+        self.assertEqual(D("0.65"), amounts["BTC"].value)
+        self.assertEqual(D("0.30"), amounts["ETH"].value)
 
-        ticker = portfolio.Trade.get_ticker("ETH", "XVG", market)
-        self.assertEqual(0.0625, ticker["average"])
-        self.assertTrue(ticker["inverted"])
-        self.assertIn("original", ticker)
-        self.assertEqual(10, ticker["original"]["bid"])
+        amounts = portfolio.BalanceStore.in_currency("BTC", market, compute_value="bid")
+        self.assertEqual(D("0.65"), amounts["BTC"].value)
+        self.assertEqual(D("0.27"), amounts["ETH"].value)
 
-        ticker = portfolio.Trade.get_ticker("XVG", "XMR", market)
-        self.assertIsNone(ticker)
+        amounts = portfolio.BalanceStore.in_currency("BTC", market, compute_value="bid", type="exchange_used")
+        self.assertEqual(D("0.30"), amounts["BTC"].value)
+        self.assertEqual(0, amounts["ETH"].value)
 
-        market.fetch_ticker.assert_has_calls([
-            mock.call("ETH/ETC"),
-            mock.call("ETH/XVG"),
-            mock.call("XVG/ETH"),
-            mock.call("XVG/XMR"),
-            mock.call("XMR/XVG"),
-            ])
+    def test_fetch_balances(self):
+        market = mock.Mock()
+        market.fetch_all_balances.return_value = self.fetch_balance
 
-        market2 = mock.Mock()
-        market2.fetch_ticker.side_effect = [
-                { "bid": 1, "ask": 3 },
-                { "bid": 1.2, "ask": 3.5 },
-                ]
-        ticker1 = portfolio.Trade.get_ticker("ETH", "ETC", market2)
-        ticker2 = portfolio.Trade.get_ticker("ETH", "ETC", market2)
-        ticker3 = portfolio.Trade.get_ticker("ETC", "ETH", market2)
-        market2.fetch_ticker.assert_called_once_with("ETH/ETC")
-        self.assertEqual(1, ticker1["bid"])
-        self.assertDictEqual(ticker1, ticker2)
-        self.assertDictEqual(ticker1, ticker3["original"])
+        portfolio.BalanceStore.fetch_balances(market)
+        self.assertNotIn("ETC", portfolio.BalanceStore.currencies())
+        self.assertListEqual(["USDT", "XVG", "XMR"], list(portfolio.BalanceStore.currencies()))
 
-        ticker4 = portfolio.Trade.get_ticker("ETH", "ETC", market2, refresh=True)
-        ticker5 = portfolio.Trade.get_ticker("ETH", "ETC", market2)
-        self.assertEqual(1.2, ticker4["bid"])
-        self.assertDictEqual(ticker4, ticker5)
+        portfolio.BalanceStore.all["ETC"] = portfolio.Balance("ETC", {
+            "exchange_total": "1", "exchange_free": "0",
+            "exchange_used": "1" })
+        portfolio.BalanceStore.fetch_balances(market)
+        self.assertEqual(0, portfolio.BalanceStore.all["ETC"].total)
+        self.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(portfolio.BalanceStore.currencies()))
 
-        market3 = mock.Mock()
-        market3.fetch_ticker.side_effect = [
-                { "bid": 1, "ask": 3 },
-                { "bid": 1.2, "ask": 3.5 },
-                ]
-        ticker6 = portfolio.Trade.get_ticker("ETH", "ETC", market3)
-        portfolio.Trade.ticker_cache_timestamp -= 4
-        ticker7 = portfolio.Trade.get_ticker("ETH", "ETC", market3)
-        portfolio.Trade.ticker_cache_timestamp -= 2
-        ticker8 = portfolio.Trade.get_ticker("ETH", "ETC", market3)
-        self.assertDictEqual(ticker6, ticker7)
-        self.assertEqual(1.2, ticker8["bid"])
+    @mock.patch.object(portfolio.Portfolio, "repartition")
+    def test_dispatch_assets(self, repartition):
+        market = mock.Mock()
+        market.fetch_all_balances.return_value = self.fetch_balance
+        portfolio.BalanceStore.fetch_balances(market)
+
+        self.assertNotIn("XEM", portfolio.BalanceStore.currencies())
+
+        repartition.return_value = {
+                "XEM": (D("0.75"), "long"),
+                "BTC": (D("0.26"), "long"),
+                }
+
+        amounts = portfolio.BalanceStore.dispatch_assets(portfolio.Amount("BTC", "10.1"))
+        self.assertIn("XEM", portfolio.BalanceStore.currencies())
+        self.assertEqual(D("2.6"), amounts["BTC"].value)
+        self.assertEqual(D("7.5"), amounts["XEM"].value)
+
+    def test_currencies(self):
+        portfolio.BalanceStore.all = {
+                "BTC": portfolio.Balance("BTC", {
+                    "total": "0.65",
+                    "exchange_total":"0.65",
+                    "exchange_free": "0.35",
+                    "exchange_used": "0.30"}),
+                "ETH": portfolio.Balance("ETH", {
+                    "total": 3,
+                    "exchange_total": 3,
+                    "exchange_free": 3,
+                    "exchange_used": 0}),
+                }
+        self.assertListEqual(["BTC", "ETH"], list(portfolio.BalanceStore.currencies()))
+
+class ComputationTest(WebMockTestCase):
+    def test_compute_value(self):
+        compute = mock.Mock()
+        portfolio.Computation.compute_value("foo", "buy", compute_value=compute)
+        compute.assert_called_with("foo", "ask")
+
+        compute.reset_mock()
+        portfolio.Computation.compute_value("foo", "sell", compute_value=compute)
+        compute.assert_called_with("foo", "bid")
+
+        compute.reset_mock()
+        portfolio.Computation.compute_value("foo", "ask", compute_value=compute)
+        compute.assert_called_with("foo", "ask")
+
+        compute.reset_mock()
+        portfolio.Computation.compute_value("foo", "bid", compute_value=compute)
+        compute.assert_called_with("foo", "bid")
+
+        compute.reset_mock()
+        portfolio.Computation.computations["test"] = compute
+        portfolio.Computation.compute_value("foo", "bid", compute_value="test")
+        compute.assert_called_with("foo", "bid")
+
+
+class TradeTest(WebMockTestCase):
 
     def test_values_assertion(self):
         value_from = portfolio.Amount("BTC", "1.0")
@@ -736,14 +871,6 @@ class TradeTest(WebMockTestCase):
         trade = portfolio.Trade(value_from, value_to, "ETH")
         self.assertEqual(0, trade.value_from.linked_to)
 
-    def test_fetch_fees(self):
-        market = mock.Mock()
-        market.fetch_fees.return_value = "Foo"
-        self.assertEqual("Foo", portfolio.Trade.fetch_fees(market))
-        market.fetch_fees.assert_called_once()
-        self.assertEqual("Foo", portfolio.Trade.fetch_fees(market))
-        market.fetch_fees.assert_called_once()
-
     def test_action(self):
         value_from = portfolio.Amount("BTC", "1.0")
         value_from.linked_to = portfolio.Amount("ETH", "10.0")
@@ -821,34 +948,6 @@ class TradeTest(WebMockTestCase):
 
         self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount)
 
-    def test_prepare_orders(self):
-        trade_mock1 = mock.Mock()
-        trade_mock2 = mock.Mock()
-
-        portfolio.Trade.trades.append(trade_mock1)
-        portfolio.Trade.trades.append(trade_mock2)
-
-        portfolio.Trade.prepare_orders()
-        trade_mock1.prepare_order.assert_called_with(compute_value="default")
-        trade_mock2.prepare_order.assert_called_with(compute_value="default")
-
-        portfolio.Trade.prepare_orders(compute_value="bla")
-        trade_mock1.prepare_order.assert_called_with(compute_value="bla")
-        trade_mock2.prepare_order.assert_called_with(compute_value="bla")
-
-        trade_mock1.prepare_order.reset_mock()
-        trade_mock2.prepare_order.reset_mock()
-
-        trade_mock1.action = "foo"
-        trade_mock2.action = "bar"
-        portfolio.Trade.prepare_orders(only="bar")
-        trade_mock1.prepare_order.assert_not_called()
-        trade_mock2.prepare_order.assert_called_with(compute_value="default")
-
-    @unittest.skip("TODO")
-    def test_compute_trades(self):
-        pass
-
     @unittest.skip("TODO")
     def test_prepare_order(self):
         pass
@@ -857,77 +956,6 @@ class TradeTest(WebMockTestCase):
     def test_update_order(self):
         pass
 
-    @unittest.skip("TODO")
-    def test_follow_orders(self):
-        pass
-
-    @unittest.skip("TODO")
-    def test_move_balances(self):
-        pass
-
-    def test_all_orders(self):
-        trade_mock1 = mock.Mock()
-        trade_mock2 = mock.Mock()
-
-        order_mock1 = mock.Mock()
-        order_mock2 = mock.Mock()
-        order_mock3 = mock.Mock()
-
-        trade_mock1.orders = [order_mock1, order_mock2]
-        trade_mock2.orders = [order_mock3]
-
-        order_mock1.status = "pending"
-        order_mock2.status = "open"
-        order_mock3.status = "open"
-
-        portfolio.Trade.trades.append(trade_mock1)
-        portfolio.Trade.trades.append(trade_mock2)
-
-        orders = portfolio.Trade.all_orders()
-        self.assertEqual(3, len(orders))
-
-        open_orders = portfolio.Trade.all_orders(state="open")
-        self.assertEqual(2, len(open_orders))
-        self.assertEqual([order_mock2, order_mock3], open_orders)
-
-    @mock.patch.object(portfolio.Trade, "all_orders")
-    def test_run_orders(self, all_orders):
-        order_mock1 = mock.Mock()
-        order_mock2 = mock.Mock()
-        order_mock3 = mock.Mock()
-        all_orders.return_value = [order_mock1, order_mock2, order_mock3]
-        portfolio.Trade.run_orders()
-        all_orders.assert_called_with(state="pending")
-
-        order_mock1.run.assert_called()
-        order_mock2.run.assert_called()
-        order_mock3.run.assert_called()
-
-    @mock.patch.object(portfolio.Trade, "all_orders")
-    def test_update_all_orders_status(self, all_orders):
-        order_mock1 = mock.Mock()
-        order_mock2 = mock.Mock()
-        order_mock3 = mock.Mock()
-        all_orders.return_value = [order_mock1, order_mock2, order_mock3]
-        portfolio.Trade.update_all_orders_status()
-        all_orders.assert_called_with(state="open")
-
-        order_mock1.get_status.assert_called()
-        order_mock2.get_status.assert_called()
-        order_mock3.get_status.assert_called()
-
-    def test_print_all_with_order(self):
-        trade_mock1 = mock.Mock()
-        trade_mock2 = mock.Mock()
-        trade_mock3 = mock.Mock()
-        portfolio.Trade.trades = [trade_mock1, trade_mock2, trade_mock3]
-
-        portfolio.Trade.print_all_with_order()
-
-        trade_mock1.print_with_order.assert_called()
-        trade_mock2.print_with_order.assert_called()
-        trade_mock3.print_with_order.assert_called()
-
     @mock.patch('sys.stdout', new_callable=StringIO)
     def test_print_with_order(self, mock_stdout):
         value_from = portfolio.Amount("BTC", "0.5")
@@ -951,28 +979,6 @@ class TradeTest(WebMockTestCase):
         self.assertEqual("\tMock 1", out[1])
         self.assertEqual("\tMock 2", out[2])
 
-    def test_compute_value(self):
-        compute = mock.Mock()
-        portfolio.Trade.compute_value("foo", "buy", compute_value=compute)
-        compute.assert_called_with("foo", "ask")
-
-        compute.reset_mock()
-        portfolio.Trade.compute_value("foo", "sell", compute_value=compute)
-        compute.assert_called_with("foo", "bid")
-
-        compute.reset_mock()
-        portfolio.Trade.compute_value("foo", "ask", compute_value=compute)
-        compute.assert_called_with("foo", "ask")
-
-        compute.reset_mock()
-        portfolio.Trade.compute_value("foo", "bid", compute_value=compute)
-        compute.assert_called_with("foo", "bid")
-
-        compute.reset_mock()
-        portfolio.Computation.computations["test"] = compute
-        portfolio.Trade.compute_value("foo", "bid", compute_value="test")
-        compute.assert_called_with("foo", "bid")
-
     def test__repr(self):
         value_from = portfolio.Amount("BTC", "0.5")
         value_from.linked_to = portfolio.Amount("ETH", "10.0")
@@ -1045,7 +1051,7 @@ class AcceptanceTest(WebMockTestCase):
                         "ask": D("0.0012")
                         }
             if symbol == "USDT/BTC":
-                raise portfolio.ExchangeError
+                raise helper.ExchangeError
             if symbol == "BTC/USDT":
                 return {
                         "symbol": "BTC/USDT",
@@ -1059,15 +1065,15 @@ class AcceptanceTest(WebMockTestCase):
         market.fetch_ticker.side_effect = fetch_ticker
         with mock.patch.object(portfolio.Portfolio, "repartition", return_value=repartition):
             # Action 1
-            portfolio.Balance.prepare_trades(market)
+            helper.prepare_trades(market)
 
-        balances = portfolio.Balance.known_balances
+        balances = portfolio.BalanceStore.all
         self.assertEqual(portfolio.Amount("ETH", 1), balances["ETH"].total)
         self.assertEqual(portfolio.Amount("ETC", 4), balances["ETC"].total)
         self.assertEqual(portfolio.Amount("XVG", 1000), balances["XVG"].total)
 
 
-        trades = portfolio.Trade.trades
+        trades = TradeStore.all
         self.assertEqual(portfolio.Amount("BTC", D("0.15")), trades[0].value_from)
         self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[0].value_to)
         self.assertEqual("dispose", trades[0].action)
@@ -1123,7 +1129,7 @@ class AcceptanceTest(WebMockTestCase):
         market.order_precision.return_value = 8
 
         # Action 3
-        portfolio.Trade.run_orders()
+        portfolio.TradeStore.run_orders()
 
         self.assertEqual("open", all_orders[0].status)
         self.assertEqual("open", all_orders[1].status)
@@ -1131,7 +1137,7 @@ class AcceptanceTest(WebMockTestCase):
         market.fetch_order.return_value = { "status": "closed" }
         with mock.patch.object(portfolio.time, "sleep") as sleep:
             # Action 4
-            portfolio.Trade.follow_orders(verbose=False)
+            helper.follow_orders(verbose=False)
 
             sleep.assert_called_with(30)
 
@@ -1164,16 +1170,16 @@ class AcceptanceTest(WebMockTestCase):
 
         with mock.patch.object(portfolio.Portfolio, "repartition", return_value=repartition):
             # Action 5
-            portfolio.Balance.update_trades(market, only="buy", compute_value="average")
+            helper.update_trades(market, only="buy", compute_value="average")
 
-        balances = portfolio.Balance.known_balances
+        balances = portfolio.BalanceStore.all
         self.assertEqual(portfolio.Amount("ETH", 1 / D("3")), balances["ETH"].total)
         self.assertEqual(portfolio.Amount("ETC", 4), balances["ETC"].total)
         self.assertEqual(portfolio.Amount("BTC", D("0.134")), balances["BTC"].total)
         self.assertEqual(portfolio.Amount("XVG", 0), balances["XVG"].total)
 
 
-        trades = portfolio.Trade.trades
+        trades = TradeStore.all
         self.assertEqual(portfolio.Amount("BTC", D("0.15")), trades["ETH"].value_from)
         self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades["ETH"].value_to)
         self.assertEqual("sell", trades["ETH"].action)
@@ -1232,11 +1238,11 @@ class AcceptanceTest(WebMockTestCase):
 
         # Action 7
         # TODO
-        # portfolio.Trade.run_orders()
+        # portfolio.TradeStore.run_orders()
 
         with mock.patch.object(portfolio.time, "sleep") as sleep:
             # Action 8
-            portfolio.Trade.follow_orders(verbose=False)
+            helper.follow_orders(verbose=False)
 
             sleep.assert_called_with(30)