]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blame - helper.py
Add print_balances helper
[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 = {}
0c79fad3
IB
7 for currency in BalanceStore.all:
8 if BalanceStore.all[currency].margin_free != 0:
9 needed_in_margin[currency] = 0
6ca5a1ec 10 for trade in TradeStore.all:
0c79fad3
IB
11 if trade.value_to.currency not in needed_in_margin:
12 needed_in_margin[trade.value_to.currency] = 0
6ca5a1ec 13 if trade.trade_type == "short":
6ca5a1ec
IB
14 needed_in_margin[trade.value_to.currency] += abs(trade.value_to)
15 for currency, needed in needed_in_margin.items():
16 current_balance = BalanceStore.all[currency].margin_free
17 delta = (needed - current_balance).value
18 # FIXME: don't remove too much if there are open margin position
19 if delta > 0:
20 if debug:
21 print("market.transfer_balance({}, {}, 'exchange', 'margin')".format(currency, delta))
22 else:
23 market.transfer_balance(currency, delta, "exchange", "margin")
24 elif delta < 0:
25 if debug:
26 print("market.transfer_balance({}, {}, 'margin', 'exchange')".format(currency, -delta))
27 else:
28 market.transfer_balance(currency, -delta, "margin", "exchange")
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
75def prepare_trades(market, base_currency="BTC", compute_value="average", debug=False):
76 BalanceStore.fetch_balances(market)
77 values_in_base = BalanceStore.in_currency(base_currency, market, compute_value=compute_value)
78 total_base_value = sum(values_in_base.values())
79 new_repartition = BalanceStore.dispatch_assets(total_base_value)
80 # Recompute it in case we have new currencies
81 values_in_base = BalanceStore.in_currency(base_currency, market, compute_value=compute_value)
82 TradeStore.compute_trades(values_in_base, new_repartition, market=market, debug=debug)
83
84def update_trades(market, base_currency="BTC", compute_value="average", only=None, debug=False):
85 BalanceStore.fetch_balances(market)
86 values_in_base = BalanceStore.in_currency(base_currency, market, compute_value=compute_value)
87 total_base_value = sum(values_in_base.values())
88 new_repartition = BalanceStore.dispatch_assets(total_base_value)
89 TradeStore.compute_trades(values_in_base, new_repartition, only=only, market=market, debug=debug)
90
91def prepare_trades_to_sell_all(market, base_currency="BTC", compute_value="average", debug=False):
92 BalanceStore.fetch_balances(market)
93 values_in_base = BalanceStore.in_currency(base_currency, market, compute_value=compute_value)
94 total_base_value = sum(values_in_base.values())
95 new_repartition = BalanceStore.dispatch_assets(total_base_value, repartition={ base_currency: (1, "long") })
96 TradeStore.compute_trades(values_in_base, new_repartition, market=market, debug=debug)
97
98def follow_orders(verbose=True, sleep=None):
99 if sleep is None:
100 sleep = 7 if TradeStore.debug else 30
101 tick = 0
102 while len(TradeStore.all_orders(state="open")) > 0:
103 time.sleep(sleep)
104 tick += 1
105 for order in TradeStore.all_orders(state="open"):
106 if order.get_status() != "open":
107 if verbose:
108 print("finished {}".format(order))
109 else:
110 order.trade.update_order(order, tick)
111 if verbose:
112 print("All orders finished")
113
114def print_orders(market, base_currency="BTC"):
2f0939e1 115 prepare_trades(market, base_currency=base_currency, compute_value="average", debug=True)
6ca5a1ec
IB
116 TradeStore.prepare_orders(compute_value="average")
117 for currency, balance in BalanceStore.all.items():
118 print(balance)
119 TradeStore.print_all_with_order()
120
97922ff1
IB
121def print_balances(market, base_currency="BTC"):
122 BalanceStore.fetch_balances(market)
123 for currency, balance in BalanceStore.all.items():
124 print(balance)
125 if base_currency is not None:
126 print("total:")
127 print(sum(BalanceStore.in_currency(base_currency, market).values()))
128
5a72ded7
IB
129def process_sell_needed__1_sell(market, base_currency="BTC", debug=False):
130 prepare_trades(market, base_currency=base_currency, debug=debug)
131 TradeStore.prepare_orders(compute_value="average", only="dispose")
132 print("------------------")
133 for currency, balance in BalanceStore.all.items():
134 print(balance)
135 print("------------------")
136 TradeStore.print_all_with_order()
137 print("------------------")
138 TradeStore.run_orders()
139 follow_orders()
140
2f0939e1 141def process_sell_needed__2_buy(market, base_currency="BTC", debug=False):
5a72ded7
IB
142 update_trades(market, base_currency=base_currency, debug=debug, only="acquire")
143 TradeStore.prepare_orders(compute_value="average", only="acquire")
144 print("------------------")
145 for currency, balance in BalanceStore.all.items():
146 print(balance)
147 print("------------------")
148 TradeStore.print_all_with_order()
149 print("------------------")
150 move_balances(market, debug=debug)
151 TradeStore.run_orders()
152 follow_orders()
6ca5a1ec 153
5a72ded7
IB
154def process_sell_all__1_all_sell(market, base_currency="BTC", debug=False):
155 prepare_trades_to_sell_all(market, base_currency=base_currency, debug=debug)
6ca5a1ec
IB
156 TradeStore.prepare_orders(compute_value="average")
157 print("------------------")
158 for currency, balance in BalanceStore.all.items():
159 print(balance)
160 print("------------------")
161 TradeStore.print_all_with_order()
162 print("------------------")
163 TradeStore.run_orders()
164 follow_orders()
165
5a72ded7
IB
166def process_sell_all__2_all_buy(market, base_currency="BTC", debug=False):
167 prepare_trades(market, base_currency=base_currency, debug=debug)
6ca5a1ec
IB
168 TradeStore.prepare_orders()
169 print("------------------")
170 for currency, balance in BalanceStore.all.items():
171 print(balance)
172 print("------------------")
173 TradeStore.print_all_with_order()
174 print("------------------")
175 move_balances(market, debug=debug)
176 TradeStore.run_orders()
177 follow_orders()
178
179