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