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
, **kwargs
):
38 return inspect
.getsource(element
).strip()
39 elif hasattr(element
, "as_json"):
40 return element
.as_json()
44 args
= { k: as_json(v) for k, v in kwargs.items() }
45 args_str
= ["{}={}".format(k
, v
) for k
, v
in args
.items()]
46 self
.print_log("-" * (len(stage
) + 8))
47 self
.print_log("[Stage] {} {}".format(stage
, ", ".join(args_str
)))
55 def log_balances(self
, tag
=None):
56 self
.print_log("[Balance]")
57 for currency
, balance
in self
.market
.balances
.all
.items():
58 self
.print_log("\t{}".format(balance
))
63 "balances": self
.market
.balances
.as_json()
66 def log_tickers(self
, amounts
, other_currency
,
70 if callable(compute_value
):
71 compute_value
= inspect
.getsource(compute_value
).strip()
73 for currency
, amount
in amounts
.items():
74 values
[currency
] = amount
.as_json()["value"]
75 rates
[currency
] = amount
.rate
78 "compute_value": compute_value
,
80 "currency": other_currency
,
83 "total": sum(amounts
.values()).as_json()["value"]
86 def log_dispatch(self
, amount
, amounts
, liquidity
, repartition
):
89 "liquidity": liquidity
,
90 "repartition_ratio": repartition
,
91 "total_amount": amount
.as_json(),
92 "repartition": { k: v.as_json()["value"] for k, v in amounts.items() }
95 def log_trades(self
, matching_and_trades
, only
):
97 for matching
, trade
in matching_and_trades
:
98 trade_json
= trade
.as_json()
99 trade_json
["skipped"] = not matching
100 trades
.append(trade_json
)
105 "debug": self
.market
.debug
,
109 def log_orders(self
, orders
, tick
=None, only
=None, compute_value
=None):
110 if callable(compute_value
):
111 compute_value
= inspect
.getsource(compute_value
).strip()
112 self
.print_log("[Orders]")
113 self
.market
.trades
.print_all_with_order(ind
="\t")
117 "compute_value": compute_value
,
119 "orders": [order
.as_json() for order
in orders
if order
is not None]
122 def log_order(self
, order
, tick
, finished
=False, update
=None,
123 new_order
=None, compute_value
=None):
124 if callable(compute_value
):
125 compute_value
= inspect
.getsource(compute_value
).strip()
127 self
.print_log("[Order] Finished {}".format(order
))
128 elif update
== "waiting":
129 self
.print_log("[Order] {}, tick {}, waiting".format(order
, tick
))
130 elif update
== "adjusting":
131 self
.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order
, tick
, new_order
))
132 elif update
== "market_fallback":
133 self
.print_log("[Order] {}, tick {}, fallbacking to market value".format(order
, tick
))
134 elif update
== "market_adjust":
135 self
.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order
, tick
, new_order
))
141 "order": order
.as_json(),
142 "compute_value": compute_value
,
143 "new_order": new_order
.as_json() if new_order
is not None else None
146 def log_move_balances(self
, needed
, moving
):
148 "type": "move_balances",
149 "debug": self
.market
.debug
,
150 "needed": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in needed.items() }
,
151 "moving": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in moving.items() }
,
154 def log_http_request(self
, method
, url
, body
, headers
, response
):
156 "type": "http_request",
161 "status": response
.status_code
,
162 "response": response
.text
165 def log_error(self
, action
, message
=None, exception
=None):
166 self
.print_log("[Error] {}".format(action
))
167 if exception
is not None:
168 self
.print_log(str("\t{}: {}".format(exception
.__class
__.__name
__, exception
)))
169 if message
is not None:
170 self
.print_log("\t{}".format(message
))
175 "exception_class": exception
.__class
__.__name
__ if exception
is not None else None,
176 "exception_message": str(exception
) if exception
is not None else None,
180 def log_debug_action(self
, action
):
181 self
.print_log("[Debug] {}".format(action
))
184 "type": "debug_action",
189 def __init__(self
, market
):
193 def currencies(self
):
194 return self
.all
.keys()
196 def in_currency(self
, other_currency
, compute_value
="average", type="total"):
198 for currency
, balance
in self
.all
.items():
199 other_currency_amount
= getattr(balance
, type)\
200 .in_currency(other_currency
, self
.market
, compute_value
=compute_value
)
201 amounts
[currency
] = other_currency_amount
202 self
.market
.report
.log_tickers(amounts
, other_currency
,
206 def fetch_balances(self
, tag
=None):
207 all_balances
= self
.market
.ccxt
.fetch_all_balances()
208 for currency
, balance
in all_balances
.items():
209 if balance
["exchange_total"] != 0 or balance
["margin_total"] != 0 or \
210 currency
in self
.all
:
211 self
.all
[currency
] = portfolio
.Balance(currency
, balance
)
212 self
.market
.report
.log_balances(tag
=tag
)
214 def dispatch_assets(self
, amount
, liquidity
="medium", repartition
=None):
215 if repartition
is None:
216 repartition
= portfolio
.Portfolio
.repartition(self
.market
, liquidity
=liquidity
)
217 sum_ratio
= sum([v
[0] for k
, v
in repartition
.items()])
219 for currency
, (ptt
, trade_type
) in repartition
.items():
220 amounts
[currency
] = ptt
* amount
/ sum_ratio
221 if trade_type
== "short":
222 amounts
[currency
] = - amounts
[currency
]
223 self
.all
.setdefault(currency
, portfolio
.Balance(currency
, {}))
224 self
.market
.report
.log_dispatch(amount
, amounts
, liquidity
, repartition
)
228 return { k: v.as_json() for k, v in self.all.items() }
231 def __init__(self
, market
):
237 return list(filter(lambda t
: not t
.is_fullfiled
, self
.all
))
239 def compute_trades(self
, values_in_base
, new_repartition
, only
=None):
241 base_currency
= sum(values_in_base
.values()).currency
242 for currency
in self
.market
.balances
.currencies():
243 if currency
== base_currency
:
245 value_from
= values_in_base
.get(currency
, portfolio
.Amount(base_currency
, 0))
246 value_to
= new_repartition
.get(currency
, portfolio
.Amount(base_currency
, 0))
248 if value_from
.value
* value_to
.value
< 0:
249 computed_trades
.append(self
.trade_if_matching(
250 value_from
, portfolio
.Amount(base_currency
, 0),
251 currency
, only
=only
))
252 computed_trades
.append(self
.trade_if_matching(
253 portfolio
.Amount(base_currency
, 0), value_to
,
254 currency
, only
=only
))
256 computed_trades
.append(self
.trade_if_matching(
257 value_from
, value_to
,
258 currency
, only
=only
))
259 for matching
, trade
in computed_trades
:
261 self
.all
.append(trade
)
262 self
.market
.report
.log_trades(computed_trades
, only
)
264 def trade_if_matching(self
, value_from
, value_to
, currency
,
266 trade
= portfolio
.Trade(value_from
, value_to
, currency
,
268 matching
= only
is None or trade
.action
== only
269 return [matching
, trade
]
271 def prepare_orders(self
, only
=None, compute_value
="default"):
273 for trade
in self
.pending
:
274 if only
is None or trade
.action
== only
:
275 orders
.append(trade
.prepare_order(compute_value
=compute_value
))
276 self
.market
.report
.log_orders(orders
, only
, compute_value
)
278 def print_all_with_order(self
, ind
=""):
279 for trade
in self
.all
:
280 trade
.print_with_order(ind
=ind
)
282 def run_orders(self
):
283 orders
= self
.all_orders(state
="pending")
286 self
.market
.report
.log_stage("run_orders")
287 self
.market
.report
.log_orders(orders
)
289 def all_orders(self
, state
=None):
290 all_orders
= sum(map(lambda v
: v
.orders
, self
.all
), [])
294 return list(filter(lambda o
: o
.status
== state
, all_orders
))
296 def update_all_orders_status(self
):
297 for order
in self
.all_orders(state
="open"):