]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blame - helper.py
Add report store to store messages and logs
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git] / helper.py
CommitLineData
6ca5a1ec
IB
1import time
2from ccxt import ExchangeError
3from store import *
4
5def move_balances(market, debug=False):
6 needed_in_margin = {}
3d0247f9
IB
7 moving_to_margin = {}
8
0c79fad3
IB
9 for currency in BalanceStore.all:
10 if BalanceStore.all[currency].margin_free != 0:
11 needed_in_margin[currency] = 0
6ca5a1ec 12 for trade in TradeStore.all:
0c79fad3
IB
13 if trade.value_to.currency not in needed_in_margin:
14 needed_in_margin[trade.value_to.currency] = 0
6ca5a1ec 15 if trade.trade_type == "short":
6ca5a1ec
IB
16 needed_in_margin[trade.value_to.currency] += abs(trade.value_to)
17 for currency, needed in needed_in_margin.items():
18 current_balance = BalanceStore.all[currency].margin_free
3d0247f9
IB
19 moving_to_margin[currency] = (needed - current_balance)
20 delta = moving_to_margin[currency].value
21 if debug:
22 ReportStore.log_debug_action("Moving {} from exchange to margin".format(moving_to_margin[currency]))
23 continue
6ca5a1ec 24 if delta > 0:
3d0247f9 25 market.transfer_balance(currency, delta, "exchange", "margin")
6ca5a1ec 26 elif delta < 0:
3d0247f9
IB
27 market.transfer_balance(currency, -delta, "margin", "exchange")
28 ReportStore.log_move_balances(needed_in_margin, moving_to_margin, debug)
6ca5a1ec
IB
29
30 BalanceStore.fetch_balances(market)
31
32ticker_cache = {}
33ticker_cache_timestamp = time.time()
34def get_ticker(c1, c2, market, refresh=False):
35 global ticker_cache, ticker_cache_timestamp
36 def invert(ticker):
37 return {
38 "inverted": True,
39 "average": (1/ticker["bid"] + 1/ticker["ask"]) / 2,
40 "original": ticker,
41 }
42 def augment_ticker(ticker):
43 ticker.update({
44 "inverted": False,
45 "average": (ticker["bid"] + ticker["ask"] ) / 2,
46 })
47
48 if time.time() - ticker_cache_timestamp > 5:
49 ticker_cache = {}
50 ticker_cache_timestamp = time.time()
51 elif not refresh:
52 if (c1, c2, market.__class__) in ticker_cache:
53 return ticker_cache[(c1, c2, market.__class__)]
54 if (c2, c1, market.__class__) in ticker_cache:
55 return invert(ticker_cache[(c2, c1, market.__class__)])
56
57 try:
58 ticker_cache[(c1, c2, market.__class__)] = market.fetch_ticker("{}/{}".format(c1, c2))
59 augment_ticker(ticker_cache[(c1, c2, market.__class__)])
60 except ExchangeError:
61 try:
62 ticker_cache[(c2, c1, market.__class__)] = market.fetch_ticker("{}/{}".format(c2, c1))
63 augment_ticker(ticker_cache[(c2, c1, market.__class__)])
64 except ExchangeError:
65 ticker_cache[(c1, c2, market.__class__)] = None
66 return get_ticker(c1, c2, market)
67
68fees_cache = {}
69def fetch_fees(market):
70 global fees_cache
71 if market.__class__ not in fees_cache:
72 fees_cache[market.__class__] = market.fetch_fees()
73 return fees_cache[market.__class__]
74
e246023e 75def prepare_trades(market, base_currency="BTC", liquidity="medium", compute_value="average", debug=False):
3d0247f9 76 ReportStore.log_stage("prepare_trades")
6ca5a1ec
IB
77 BalanceStore.fetch_balances(market)
78 values_in_base = BalanceStore.in_currency(base_currency, market, compute_value=compute_value)
79 total_base_value = sum(values_in_base.values())
e246023e 80 new_repartition = BalanceStore.dispatch_assets(total_base_value, liquidity=liquidity)
6ca5a1ec
IB
81 # Recompute it in case we have new currencies
82 values_in_base = BalanceStore.in_currency(base_currency, market, compute_value=compute_value)
83 TradeStore.compute_trades(values_in_base, new_repartition, market=market, debug=debug)
84
e246023e 85def update_trades(market, base_currency="BTC", liquidity="medium", compute_value="average", only=None, debug=False):
3d0247f9 86 ReportStore.log_stage("update_trades")
6ca5a1ec
IB
87 BalanceStore.fetch_balances(market)
88 values_in_base = BalanceStore.in_currency(base_currency, market, compute_value=compute_value)
89 total_base_value = sum(values_in_base.values())
e246023e 90 new_repartition = BalanceStore.dispatch_assets(total_base_value, liquidity=liquidity)
6ca5a1ec
IB
91 TradeStore.compute_trades(values_in_base, new_repartition, only=only, market=market, debug=debug)
92
93def prepare_trades_to_sell_all(market, base_currency="BTC", compute_value="average", debug=False):
3d0247f9 94 ReportStore.log_stage("prepare_trades_to_sell_all")
6ca5a1ec
IB
95 BalanceStore.fetch_balances(market)
96 values_in_base = BalanceStore.in_currency(base_currency, market, compute_value=compute_value)
97 total_base_value = sum(values_in_base.values())
98 new_repartition = BalanceStore.dispatch_assets(total_base_value, repartition={ base_currency: (1, "long") })
99 TradeStore.compute_trades(values_in_base, new_repartition, market=market, debug=debug)
100
3d0247f9 101def follow_orders(sleep=None):
6ca5a1ec
IB
102 if sleep is None:
103 sleep = 7 if TradeStore.debug else 30
3d0247f9
IB
104 if TradeStore.debug:
105 ReportStore.log_debug_action("Set follow_orders tick to {}s".format(sleep))
6ca5a1ec 106 tick = 0
3d0247f9 107 ReportStore.log_stage("follow_orders_begin")
6ca5a1ec
IB
108 while len(TradeStore.all_orders(state="open")) > 0:
109 time.sleep(sleep)
110 tick += 1
3d0247f9
IB
111 open_orders = TradeStore.all_orders(state="open")
112 ReportStore.log_stage("follow_orders_tick_{}".format(tick))
113 ReportStore.log_orders(open_orders, tick=tick)
114 for order in open_orders:
6ca5a1ec 115 if order.get_status() != "open":
3d0247f9 116 ReportStore.log_order(order, tick, finished=True)
6ca5a1ec
IB
117 else:
118 order.trade.update_order(order, tick)
3d0247f9 119 ReportStore.log_stage("follow_orders_end")
6ca5a1ec
IB
120
121def print_orders(market, base_currency="BTC"):
3d0247f9 122 ReportStore.log_stage("print_orders")
2f0939e1 123 prepare_trades(market, base_currency=base_currency, compute_value="average", debug=True)
6ca5a1ec 124 TradeStore.prepare_orders(compute_value="average")
6ca5a1ec 125
97922ff1
IB
126def print_balances(market, base_currency="BTC"):
127 BalanceStore.fetch_balances(market)
97922ff1 128 if base_currency is not None:
3d0247f9
IB
129 ReportStore.print_log("total:")
130 ReportStore.print_log(sum(BalanceStore.in_currency(base_currency, market).values()))
97922ff1 131
e246023e 132def process_sell_needed__1_sell(market, liquidity="medium", base_currency="BTC", debug=False):
3d0247f9 133 ReportStore.log_stage("process_sell_needed__1_sell_begin")
e246023e 134 prepare_trades(market, liquidity=liquidity, base_currency=base_currency, debug=debug)
5a72ded7 135 TradeStore.prepare_orders(compute_value="average", only="dispose")
5a72ded7
IB
136 TradeStore.run_orders()
137 follow_orders()
3d0247f9 138 ReportStore.log_stage("process_sell_needed__1_sell_end")
5a72ded7 139
e246023e 140def process_sell_needed__2_buy(market, liquidity="medium", base_currency="BTC", debug=False):
3d0247f9 141 ReportStore.log_stage("process_sell_needed__2_buy_begin")
e246023e 142 update_trades(market, base_currency=base_currency, liquidity=liquidity, debug=debug, only="acquire")
5a72ded7 143 TradeStore.prepare_orders(compute_value="average", only="acquire")
5a72ded7
IB
144 move_balances(market, debug=debug)
145 TradeStore.run_orders()
146 follow_orders()
3d0247f9 147 ReportStore.log_stage("process_sell_needed__2_buy_end")
6ca5a1ec 148
e246023e 149def process_sell_all__1_all_sell(market, base_currency="BTC", debug=False, liquidity="medium"):
3d0247f9 150 ReportStore.log_stage("process_sell_all__1_all_sell_begin")
5a72ded7 151 prepare_trades_to_sell_all(market, base_currency=base_currency, debug=debug)
6ca5a1ec 152 TradeStore.prepare_orders(compute_value="average")
6ca5a1ec
IB
153 TradeStore.run_orders()
154 follow_orders()
3d0247f9 155 ReportStore.log_stage("process_sell_all__1_all_sell_end")
6ca5a1ec 156
e246023e 157def process_sell_all__2_all_buy(market, base_currency="BTC", debug=False, liquidity="medium"):
3d0247f9 158 ReportStore.log_stage("process_sell_all__2_all_buy_begin")
e246023e
IB
159 prepare_trades(market, liquidity=liquidity, base_currency=base_currency, debug=debug)
160 TradeStore.prepare_orders(compute_value="average")
6ca5a1ec
IB
161 move_balances(market, debug=debug)
162 TradeStore.run_orders()
163 follow_orders()
3d0247f9 164 ReportStore.log_stage("process_sell_all__2_all_buy_end")
6ca5a1ec
IB
165
166