]>
Commit | Line | Data |
---|---|---|
6ca5a1ec | 1 | import portfolio |
3d0247f9 IB |
2 | import simplejson as json |
3 | from decimal import Decimal as D, ROUND_DOWN | |
4 | from datetime import date, datetime | |
6ca5a1ec | 5 | |
3d0247f9 IB |
6 | __all__ = ["BalanceStore", "ReportStore", "TradeStore"] |
7 | ||
8 | class ReportStore: | |
f86ee140 IB |
9 | def __init__(self, market, verbose_print=True): |
10 | self.market = market | |
11 | self.verbose_print = verbose_print | |
3d0247f9 | 12 | |
f86ee140 IB |
13 | self.logs = [] |
14 | ||
15 | def print_log(self, message): | |
3d0247f9 | 16 | message = str(message) |
f86ee140 | 17 | if self.verbose_print: |
3d0247f9 IB |
18 | print(message) |
19 | ||
f86ee140 | 20 | def add_log(self, hash_): |
3d0247f9 | 21 | hash_["date"] = datetime.now() |
f86ee140 | 22 | self.logs.append(hash_) |
3d0247f9 | 23 | |
f86ee140 | 24 | def to_json(self): |
3d0247f9 IB |
25 | def default_json_serial(obj): |
26 | if isinstance(obj, (datetime, date)): | |
27 | return obj.isoformat() | |
be54a201 | 28 | return str(obj) |
f86ee140 | 29 | return json.dumps(self.logs, default=default_json_serial) |
3d0247f9 | 30 | |
f86ee140 IB |
31 | def set_verbose(self, verbose_print): |
32 | self.verbose_print = verbose_print | |
3d0247f9 | 33 | |
f86ee140 IB |
34 | def log_stage(self, stage): |
35 | self.print_log("-" * (len(stage) + 8)) | |
36 | self.print_log("[Stage] {}".format(stage)) | |
3d0247f9 | 37 | |
f86ee140 | 38 | self.add_log({ |
3d0247f9 IB |
39 | "type": "stage", |
40 | "stage": stage, | |
41 | }) | |
42 | ||
f86ee140 IB |
43 | def log_balances(self, tag=None): |
44 | self.print_log("[Balance]") | |
45 | for currency, balance in self.market.balances.all.items(): | |
46 | self.print_log("\t{}".format(balance)) | |
3d0247f9 | 47 | |
f86ee140 | 48 | self.add_log({ |
3d0247f9 | 49 | "type": "balance", |
18167a3c | 50 | "tag": tag, |
f86ee140 | 51 | "balances": self.market.balances.as_json() |
3d0247f9 IB |
52 | }) |
53 | ||
f86ee140 | 54 | def log_tickers(self, amounts, other_currency, |
3d0247f9 IB |
55 | compute_value, type): |
56 | values = {} | |
57 | rates = {} | |
58 | for currency, amount in amounts.items(): | |
59 | values[currency] = amount.as_json()["value"] | |
60 | rates[currency] = amount.rate | |
f86ee140 | 61 | self.add_log({ |
3d0247f9 IB |
62 | "type": "tickers", |
63 | "compute_value": compute_value, | |
64 | "balance_type": type, | |
65 | "currency": other_currency, | |
66 | "balances": values, | |
67 | "rates": rates, | |
68 | "total": sum(amounts.values()).as_json()["value"] | |
69 | }) | |
70 | ||
f86ee140 IB |
71 | def log_dispatch(self, amount, amounts, liquidity, repartition): |
72 | self.add_log({ | |
3d0247f9 IB |
73 | "type": "dispatch", |
74 | "liquidity": liquidity, | |
75 | "repartition_ratio": repartition, | |
76 | "total_amount": amount.as_json(), | |
77 | "repartition": { k: v.as_json()["value"] for k, v in amounts.items() } | |
78 | }) | |
79 | ||
f86ee140 | 80 | def log_trades(self, matching_and_trades, only): |
3d0247f9 IB |
81 | trades = [] |
82 | for matching, trade in matching_and_trades: | |
83 | trade_json = trade.as_json() | |
84 | trade_json["skipped"] = not matching | |
85 | trades.append(trade_json) | |
86 | ||
f86ee140 | 87 | self.add_log({ |
3d0247f9 IB |
88 | "type": "trades", |
89 | "only": only, | |
f86ee140 | 90 | "debug": self.market.debug, |
3d0247f9 IB |
91 | "trades": trades |
92 | }) | |
93 | ||
f86ee140 IB |
94 | def log_orders(self, orders, tick=None, only=None, compute_value=None): |
95 | self.print_log("[Orders]") | |
96 | self.market.trades.print_all_with_order(ind="\t") | |
97 | self.add_log({ | |
3d0247f9 IB |
98 | "type": "orders", |
99 | "only": only, | |
100 | "compute_value": compute_value, | |
101 | "tick": tick, | |
102 | "orders": [order.as_json() for order in orders if order is not None] | |
103 | }) | |
104 | ||
f86ee140 | 105 | def log_order(self, order, tick, finished=False, update=None, |
3d0247f9 IB |
106 | new_order=None, compute_value=None): |
107 | if finished: | |
f86ee140 | 108 | self.print_log("[Order] Finished {}".format(order)) |
3d0247f9 | 109 | elif update == "waiting": |
f86ee140 | 110 | self.print_log("[Order] {}, tick {}, waiting".format(order, tick)) |
3d0247f9 | 111 | elif update == "adjusting": |
f86ee140 | 112 | self.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order)) |
3d0247f9 | 113 | elif update == "market_fallback": |
f86ee140 | 114 | self.print_log("[Order] {}, tick {}, fallbacking to market value".format(order, tick)) |
3d0247f9 | 115 | elif update == "market_adjust": |
f86ee140 | 116 | self.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order, tick, new_order)) |
3d0247f9 | 117 | |
f86ee140 | 118 | self.add_log({ |
3d0247f9 IB |
119 | "type": "order", |
120 | "tick": tick, | |
121 | "update": update, | |
122 | "order": order.as_json(), | |
123 | "compute_value": compute_value, | |
124 | "new_order": new_order.as_json() if new_order is not None else None | |
125 | }) | |
126 | ||
f86ee140 IB |
127 | def log_move_balances(self, needed, moving): |
128 | self.add_log({ | |
3d0247f9 | 129 | "type": "move_balances", |
f86ee140 | 130 | "debug": self.market.debug, |
3d0247f9 IB |
131 | "needed": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in needed.items() }, |
132 | "moving": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in moving.items() }, | |
133 | }) | |
134 | ||
f86ee140 IB |
135 | def log_http_request(self, method, url, body, headers, response): |
136 | self.add_log({ | |
3d0247f9 IB |
137 | "type": "http_request", |
138 | "method": method, | |
139 | "url": url, | |
140 | "body": body, | |
141 | "headers": headers, | |
142 | "status": response.status_code, | |
143 | "response": response.text | |
144 | }) | |
145 | ||
f86ee140 IB |
146 | def log_error(self, action, message=None, exception=None): |
147 | self.print_log("[Error] {}".format(action)) | |
3d0247f9 | 148 | if exception is not None: |
f86ee140 | 149 | self.print_log(str("\t{}: {}".format(exception.__class__.__name__, exception))) |
3d0247f9 | 150 | if message is not None: |
f86ee140 | 151 | self.print_log("\t{}".format(message)) |
3d0247f9 | 152 | |
f86ee140 | 153 | self.add_log({ |
3d0247f9 IB |
154 | "type": "error", |
155 | "action": action, | |
156 | "exception_class": exception.__class__.__name__ if exception is not None else None, | |
157 | "exception_message": str(exception) if exception is not None else None, | |
158 | "message": message, | |
159 | }) | |
160 | ||
f86ee140 IB |
161 | def log_debug_action(self, action): |
162 | self.print_log("[Debug] {}".format(action)) | |
3d0247f9 | 163 | |
f86ee140 | 164 | self.add_log({ |
3d0247f9 IB |
165 | "type": "debug_action", |
166 | "action": action, | |
167 | }) | |
6ca5a1ec IB |
168 | |
169 | class BalanceStore: | |
f86ee140 IB |
170 | def __init__(self, market): |
171 | self.market = market | |
172 | self.all = {} | |
6ca5a1ec | 173 | |
f86ee140 IB |
174 | def currencies(self): |
175 | return self.all.keys() | |
6ca5a1ec | 176 | |
f86ee140 | 177 | def in_currency(self, other_currency, compute_value="average", type="total"): |
6ca5a1ec | 178 | amounts = {} |
f86ee140 | 179 | for currency, balance in self.all.items(): |
6ca5a1ec | 180 | other_currency_amount = getattr(balance, type)\ |
f86ee140 | 181 | .in_currency(other_currency, self.market, compute_value=compute_value) |
6ca5a1ec | 182 | amounts[currency] = other_currency_amount |
f86ee140 | 183 | self.market.report.log_tickers(amounts, other_currency, |
3d0247f9 | 184 | compute_value, type) |
6ca5a1ec IB |
185 | return amounts |
186 | ||
f86ee140 IB |
187 | def fetch_balances(self, tag=None): |
188 | all_balances = self.market.ccxt.fetch_all_balances() | |
6ca5a1ec IB |
189 | for currency, balance in all_balances.items(): |
190 | if balance["exchange_total"] != 0 or balance["margin_total"] != 0 or \ | |
f86ee140 IB |
191 | currency in self.all: |
192 | self.all[currency] = portfolio.Balance(currency, balance) | |
193 | self.market.report.log_balances(tag=tag) | |
6ca5a1ec | 194 | |
f86ee140 | 195 | def dispatch_assets(self, amount, liquidity="medium", repartition=None): |
6ca5a1ec | 196 | if repartition is None: |
f86ee140 | 197 | repartition = portfolio.Portfolio.repartition(self.market, liquidity=liquidity) |
6ca5a1ec IB |
198 | sum_ratio = sum([v[0] for k, v in repartition.items()]) |
199 | amounts = {} | |
200 | for currency, (ptt, trade_type) in repartition.items(): | |
201 | amounts[currency] = ptt * amount / sum_ratio | |
202 | if trade_type == "short": | |
203 | amounts[currency] = - amounts[currency] | |
f86ee140 IB |
204 | if currency not in self.all: |
205 | self.all[currency] = portfolio.Balance(currency, {}) | |
206 | self.market.report.log_dispatch(amount, amounts, liquidity, repartition) | |
6ca5a1ec IB |
207 | return amounts |
208 | ||
f86ee140 IB |
209 | def as_json(self): |
210 | return { k: v.as_json() for k, v in self.all.items() } | |
3d0247f9 | 211 | |
6ca5a1ec | 212 | class TradeStore: |
f86ee140 IB |
213 | def __init__(self, market): |
214 | self.market = market | |
215 | self.all = [] | |
6ca5a1ec | 216 | |
f86ee140 | 217 | def compute_trades(self, values_in_base, new_repartition, only=None): |
3d0247f9 | 218 | computed_trades = [] |
6ca5a1ec | 219 | base_currency = sum(values_in_base.values()).currency |
f86ee140 | 220 | for currency in self.market.balances.currencies(): |
6ca5a1ec IB |
221 | if currency == base_currency: |
222 | continue | |
223 | value_from = values_in_base.get(currency, portfolio.Amount(base_currency, 0)) | |
224 | value_to = new_repartition.get(currency, portfolio.Amount(base_currency, 0)) | |
1aa7d4fa | 225 | |
6ca5a1ec | 226 | if value_from.value * value_to.value < 0: |
f86ee140 | 227 | computed_trades.append(self.trade_if_matching( |
1aa7d4fa | 228 | value_from, portfolio.Amount(base_currency, 0), |
f86ee140 IB |
229 | currency, only=only)) |
230 | computed_trades.append(self.trade_if_matching( | |
1aa7d4fa | 231 | portfolio.Amount(base_currency, 0), value_to, |
f86ee140 | 232 | currency, only=only)) |
6ca5a1ec | 233 | else: |
f86ee140 | 234 | computed_trades.append(self.trade_if_matching( |
3d0247f9 | 235 | value_from, value_to, |
f86ee140 | 236 | currency, only=only)) |
3d0247f9 IB |
237 | for matching, trade in computed_trades: |
238 | if matching: | |
f86ee140 IB |
239 | self.all.append(trade) |
240 | self.market.report.log_trades(computed_trades, only) | |
1aa7d4fa | 241 | |
f86ee140 IB |
242 | def trade_if_matching(self, value_from, value_to, currency, |
243 | only=None): | |
1aa7d4fa | 244 | trade = portfolio.Trade(value_from, value_to, currency, |
f86ee140 | 245 | self.market) |
3d0247f9 IB |
246 | matching = only is None or trade.action == only |
247 | return [matching, trade] | |
6ca5a1ec | 248 | |
f86ee140 | 249 | def prepare_orders(self, only=None, compute_value="default"): |
3d0247f9 | 250 | orders = [] |
f86ee140 | 251 | for trade in self.all: |
6ca5a1ec | 252 | if only is None or trade.action == only: |
3d0247f9 | 253 | orders.append(trade.prepare_order(compute_value=compute_value)) |
f86ee140 | 254 | self.market.report.log_orders(orders, only, compute_value) |
6ca5a1ec | 255 | |
f86ee140 IB |
256 | def print_all_with_order(self, ind=""): |
257 | for trade in self.all: | |
3d0247f9 | 258 | trade.print_with_order(ind=ind) |
6ca5a1ec | 259 | |
f86ee140 IB |
260 | def run_orders(self): |
261 | orders = self.all_orders(state="pending") | |
3d0247f9 | 262 | for order in orders: |
6ca5a1ec | 263 | order.run() |
f86ee140 IB |
264 | self.market.report.log_stage("run_orders") |
265 | self.market.report.log_orders(orders) | |
6ca5a1ec | 266 | |
f86ee140 IB |
267 | def all_orders(self, state=None): |
268 | all_orders = sum(map(lambda v: v.orders, self.all), []) | |
6ca5a1ec IB |
269 | if state is None: |
270 | return all_orders | |
271 | else: | |
272 | return list(filter(lambda o: o.status == state, all_orders)) | |
273 | ||
f86ee140 IB |
274 | def update_all_orders_status(self): |
275 | for order in self.all_orders(state="open"): | |
6ca5a1ec IB |
276 | order.get_status() |
277 | ||
278 |