2 import simplejson
as json
3 from decimal
import Decimal
as D
, ROUND_DOWN
4 from datetime
import date
, datetime
7 __all__
= ["BalanceStore", "ReportStore", "TradeStore"]
10 def __init__(self
, market
, verbose_print
=True):
12 self
.verbose_print
= verbose_print
16 def print_log(self
, message
):
17 message
= str(message
)
18 if self
.verbose_print
:
21 def add_log(self
, hash_
):
22 hash_
["date"] = datetime
.now()
23 self
.logs
.append(hash_
)
26 def default_json_serial(obj
):
27 if isinstance(obj
, (datetime
, date
)):
28 return obj
.isoformat()
30 return json
.dumps(self
.logs
, default
=default_json_serial
)
32 def set_verbose(self
, verbose_print
):
33 self
.verbose_print
= verbose_print
35 def log_stage(self
, stage
):
36 self
.print_log("-" * (len(stage
) + 8))
37 self
.print_log("[Stage] {}".format(stage
))
44 def log_balances(self
, tag
=None):
45 self
.print_log("[Balance]")
46 for currency
, balance
in self
.market
.balances
.all
.items():
47 self
.print_log("\t{}".format(balance
))
52 "balances": self
.market
.balances
.as_json()
55 def log_tickers(self
, amounts
, other_currency
,
59 if callable(compute_value
):
60 compute_value
= inspect
.getsource(compute_value
).strip()
62 for currency
, amount
in amounts
.items():
63 values
[currency
] = amount
.as_json()["value"]
64 rates
[currency
] = amount
.rate
67 "compute_value": compute_value
,
69 "currency": other_currency
,
72 "total": sum(amounts
.values()).as_json()["value"]
75 def log_dispatch(self
, amount
, amounts
, liquidity
, repartition
):
78 "liquidity": liquidity
,
79 "repartition_ratio": repartition
,
80 "total_amount": amount
.as_json(),
81 "repartition": { k: v.as_json()["value"] for k, v in amounts.items() }
84 def log_trades(self
, matching_and_trades
, only
):
86 for matching
, trade
in matching_and_trades
:
87 trade_json
= trade
.as_json()
88 trade_json
["skipped"] = not matching
89 trades
.append(trade_json
)
94 "debug": self
.market
.debug
,
98 def log_orders(self
, orders
, tick
=None, only
=None, compute_value
=None):
99 if callable(compute_value
):
100 compute_value
= inspect
.getsource(compute_value
).strip()
101 self
.print_log("[Orders]")
102 self
.market
.trades
.print_all_with_order(ind
="\t")
106 "compute_value": compute_value
,
108 "orders": [order
.as_json() for order
in orders
if order
is not None]
111 def log_order(self
, order
, tick
, finished
=False, update
=None,
112 new_order
=None, compute_value
=None):
113 if callable(compute_value
):
114 compute_value
= inspect
.getsource(compute_value
).strip()
116 self
.print_log("[Order] Finished {}".format(order
))
117 elif update
== "waiting":
118 self
.print_log("[Order] {}, tick {}, waiting".format(order
, tick
))
119 elif update
== "adjusting":
120 self
.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order
, tick
, new_order
))
121 elif update
== "market_fallback":
122 self
.print_log("[Order] {}, tick {}, fallbacking to market value".format(order
, tick
))
123 elif update
== "market_adjust":
124 self
.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order
, tick
, new_order
))
130 "order": order
.as_json(),
131 "compute_value": compute_value
,
132 "new_order": new_order
.as_json() if new_order
is not None else None
135 def log_move_balances(self
, needed
, moving
):
137 "type": "move_balances",
138 "debug": self
.market
.debug
,
139 "needed": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in needed.items() }
,
140 "moving": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in moving.items() }
,
143 def log_http_request(self
, method
, url
, body
, headers
, response
):
145 "type": "http_request",
150 "status": response
.status_code
,
151 "response": response
.text
154 def log_error(self
, action
, message
=None, exception
=None):
155 self
.print_log("[Error] {}".format(action
))
156 if exception
is not None:
157 self
.print_log(str("\t{}: {}".format(exception
.__class
__.__name
__, exception
)))
158 if message
is not None:
159 self
.print_log("\t{}".format(message
))
164 "exception_class": exception
.__class
__.__name
__ if exception
is not None else None,
165 "exception_message": str(exception
) if exception
is not None else None,
169 def log_debug_action(self
, action
):
170 self
.print_log("[Debug] {}".format(action
))
173 "type": "debug_action",
178 def __init__(self
, market
):
182 def currencies(self
):
183 return self
.all
.keys()
185 def in_currency(self
, other_currency
, compute_value
="average", type="total"):
187 for currency
, balance
in self
.all
.items():
188 other_currency_amount
= getattr(balance
, type)\
189 .in_currency(other_currency
, self
.market
, compute_value
=compute_value
)
190 amounts
[currency
] = other_currency_amount
191 self
.market
.report
.log_tickers(amounts
, other_currency
,
195 def fetch_balances(self
, tag
=None):
196 all_balances
= self
.market
.ccxt
.fetch_all_balances()
197 for currency
, balance
in all_balances
.items():
198 if balance
["exchange_total"] != 0 or balance
["margin_total"] != 0 or \
199 currency
in self
.all
:
200 self
.all
[currency
] = portfolio
.Balance(currency
, balance
)
201 self
.market
.report
.log_balances(tag
=tag
)
203 def dispatch_assets(self
, amount
, liquidity
="medium", repartition
=None):
204 if repartition
is None:
205 repartition
= portfolio
.Portfolio
.repartition(self
.market
, liquidity
=liquidity
)
206 sum_ratio
= sum([v
[0] for k
, v
in repartition
.items()])
208 for currency
, (ptt
, trade_type
) in repartition
.items():
209 amounts
[currency
] = ptt
* amount
/ sum_ratio
210 if trade_type
== "short":
211 amounts
[currency
] = - amounts
[currency
]
212 self
.all
.setdefault(currency
, portfolio
.Balance(currency
, {}))
213 self
.market
.report
.log_dispatch(amount
, amounts
, liquidity
, repartition
)
217 return { k: v.as_json() for k, v in self.all.items() }
220 def __init__(self
, market
):
226 return list(filter(lambda t
: not t
.is_fullfiled
, self
.all
))
228 def compute_trades(self
, values_in_base
, new_repartition
, only
=None):
230 base_currency
= sum(values_in_base
.values()).currency
231 for currency
in self
.market
.balances
.currencies():
232 if currency
== base_currency
:
234 value_from
= values_in_base
.get(currency
, portfolio
.Amount(base_currency
, 0))
235 value_to
= new_repartition
.get(currency
, portfolio
.Amount(base_currency
, 0))
237 if value_from
.value
* value_to
.value
< 0:
238 computed_trades
.append(self
.trade_if_matching(
239 value_from
, portfolio
.Amount(base_currency
, 0),
240 currency
, only
=only
))
241 computed_trades
.append(self
.trade_if_matching(
242 portfolio
.Amount(base_currency
, 0), value_to
,
243 currency
, only
=only
))
245 computed_trades
.append(self
.trade_if_matching(
246 value_from
, value_to
,
247 currency
, only
=only
))
248 for matching
, trade
in computed_trades
:
250 self
.all
.append(trade
)
251 self
.market
.report
.log_trades(computed_trades
, only
)
253 def trade_if_matching(self
, value_from
, value_to
, currency
,
255 trade
= portfolio
.Trade(value_from
, value_to
, currency
,
257 matching
= only
is None or trade
.action
== only
258 return [matching
, trade
]
260 def prepare_orders(self
, only
=None, compute_value
="default"):
262 for trade
in self
.pending
:
263 if only
is None or trade
.action
== only
:
264 orders
.append(trade
.prepare_order(compute_value
=compute_value
))
265 self
.market
.report
.log_orders(orders
, only
, compute_value
)
267 def print_all_with_order(self
, ind
=""):
268 for trade
in self
.all
:
269 trade
.print_with_order(ind
=ind
)
271 def run_orders(self
):
272 orders
= self
.all_orders(state
="pending")
275 self
.market
.report
.log_stage("run_orders")
276 self
.market
.report
.log_orders(orders
)
278 def all_orders(self
, state
=None):
279 all_orders
= sum(map(lambda v
: v
.orders
, self
.all
), [])
283 return list(filter(lambda o
: o
.status
== state
, all_orders
))
285 def update_all_orders_status(self
):
286 for order
in self
.all_orders(state
="open"):