4 import simplejson
as json
5 from decimal
import Decimal
as D
, ROUND_DOWN
6 from datetime
import date
, datetime
, timedelta
8 from json
import JSONDecodeError
9 from simplejson
.errors
import JSONDecodeError
as SimpleJSONDecodeError
11 __all__
= ["Portfolio", "BalanceStore", "ReportStore", "TradeStore"]
14 def __init__(self
, market
, verbose_print
=True):
16 self
.verbose_print
= verbose_print
20 def print_log(self
, message
):
21 message
= str(message
)
22 if self
.verbose_print
:
25 def add_log(self
, hash_
):
26 hash_
["date"] = datetime
.now()
27 self
.logs
.append(hash_
)
30 def default_json_serial(obj
):
31 if isinstance(obj
, (datetime
, date
)):
32 return obj
.isoformat()
34 return json
.dumps(self
.logs
, default
=default_json_serial
, indent
=" ")
36 def set_verbose(self
, verbose_print
):
37 self
.verbose_print
= verbose_print
39 def log_stage(self
, stage
, **kwargs
):
42 return inspect
.getsource(element
).strip()
43 elif hasattr(element
, "as_json"):
44 return element
.as_json()
48 args
= { k: as_json(v) for k, v in kwargs.items() }
49 args_str
= ["{}={}".format(k
, v
) for k
, v
in args
.items()]
50 self
.print_log("-" * (len(stage
) + 8))
51 self
.print_log("[Stage] {} {}".format(stage
, ", ".join(args_str
)))
59 def log_balances(self
, tag
=None):
60 self
.print_log("[Balance]")
61 for currency
, balance
in self
.market
.balances
.all
.items():
62 self
.print_log("\t{}".format(balance
))
67 "balances": self
.market
.balances
.as_json()
70 def log_tickers(self
, amounts
, other_currency
,
74 if callable(compute_value
):
75 compute_value
= inspect
.getsource(compute_value
).strip()
77 for currency
, amount
in amounts
.items():
78 values
[currency
] = amount
.as_json()["value"]
79 rates
[currency
] = amount
.rate
82 "compute_value": compute_value
,
84 "currency": other_currency
,
87 "total": sum(amounts
.values()).as_json()["value"]
90 def log_dispatch(self
, amount
, amounts
, liquidity
, repartition
):
93 "liquidity": liquidity
,
94 "repartition_ratio": repartition
,
95 "total_amount": amount
.as_json(),
96 "repartition": { k: v.as_json()["value"] for k, v in amounts.items() }
99 def log_trades(self
, matching_and_trades
, only
):
101 for matching
, trade
in matching_and_trades
:
102 trade_json
= trade
.as_json()
103 trade_json
["skipped"] = not matching
104 trades
.append(trade_json
)
109 "debug": self
.market
.debug
,
113 def log_orders(self
, orders
, tick
=None, only
=None, compute_value
=None):
114 if callable(compute_value
):
115 compute_value
= inspect
.getsource(compute_value
).strip()
116 self
.print_log("[Orders]")
117 self
.market
.trades
.print_all_with_order(ind
="\t")
121 "compute_value": compute_value
,
123 "orders": [order
.as_json() for order
in orders
if order
is not None]
126 def log_order(self
, order
, tick
, finished
=False, update
=None,
127 new_order
=None, compute_value
=None):
128 if callable(compute_value
):
129 compute_value
= inspect
.getsource(compute_value
).strip()
131 self
.print_log("[Order] Finished {}".format(order
))
132 elif update
== "waiting":
133 self
.print_log("[Order] {}, tick {}, waiting".format(order
, tick
))
134 elif update
== "adjusting":
135 self
.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order
, tick
, new_order
))
136 elif update
== "market_fallback":
137 self
.print_log("[Order] {}, tick {}, fallbacking to market value".format(order
, tick
))
138 elif update
== "market_adjust":
139 self
.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order
, tick
, new_order
))
145 "order": order
.as_json(),
146 "compute_value": compute_value
,
147 "new_order": new_order
.as_json() if new_order
is not None else None
150 def log_move_balances(self
, needed
, moving
):
152 "type": "move_balances",
153 "debug": self
.market
.debug
,
154 "needed": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in needed.items() }
,
155 "moving": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in moving.items() }
,
158 def log_http_request(self
, method
, url
, body
, headers
, response
):
160 "type": "http_request",
165 "status": response
.status_code
,
166 "response": response
.text
169 def log_error(self
, action
, message
=None, exception
=None):
170 self
.print_log("[Error] {}".format(action
))
171 if exception
is not None:
172 self
.print_log(str("\t{}: {}".format(exception
.__class
__.__name
__, exception
)))
173 if message
is not None:
174 self
.print_log("\t{}".format(message
))
179 "exception_class": exception
.__class
__.__name
__ if exception
is not None else None,
180 "exception_message": str(exception
) if exception
is not None else None,
184 def log_debug_action(self
, action
):
185 self
.print_log("[Debug] {}".format(action
))
188 "type": "debug_action",
193 def __init__(self
, market
):
197 def currencies(self
):
198 return self
.all
.keys()
200 def in_currency(self
, other_currency
, compute_value
="average", type="total"):
202 for currency
, balance
in self
.all
.items():
203 other_currency_amount
= getattr(balance
, type)\
204 .in_currency(other_currency
, self
.market
, compute_value
=compute_value
)
205 amounts
[currency
] = other_currency_amount
206 self
.market
.report
.log_tickers(amounts
, other_currency
,
210 def fetch_balances(self
, tag
=None):
211 all_balances
= self
.market
.ccxt
.fetch_all_balances()
212 for currency
, balance
in all_balances
.items():
213 if balance
["exchange_total"] != 0 or balance
["margin_total"] != 0 or \
214 currency
in self
.all
:
215 self
.all
[currency
] = portfolio
.Balance(currency
, balance
)
216 self
.market
.report
.log_balances(tag
=tag
)
218 def dispatch_assets(self
, amount
, liquidity
="medium", repartition
=None):
219 if repartition
is None:
220 repartition
= Portfolio
.repartition(liquidity
=liquidity
)
221 sum_ratio
= sum([v
[0] for k
, v
in repartition
.items()])
223 for currency
, (ptt
, trade_type
) in repartition
.items():
224 amounts
[currency
] = ptt
* amount
/ sum_ratio
225 if trade_type
== "short":
226 amounts
[currency
] = - amounts
[currency
]
227 self
.all
.setdefault(currency
, portfolio
.Balance(currency
, {}))
228 self
.market
.report
.log_dispatch(amount
, amounts
, liquidity
, repartition
)
232 return { k: v.as_json() for k, v in self.all.items() }
235 def __init__(self
, market
):
241 return list(filter(lambda t
: t
.pending
, self
.all
))
243 def compute_trades(self
, values_in_base
, new_repartition
, only
=None):
245 base_currency
= sum(values_in_base
.values()).currency
246 for currency
in self
.market
.balances
.currencies():
247 if currency
== base_currency
:
249 value_from
= values_in_base
.get(currency
, portfolio
.Amount(base_currency
, 0))
250 value_to
= new_repartition
.get(currency
, portfolio
.Amount(base_currency
, 0))
252 if value_from
.value
* value_to
.value
< 0:
253 computed_trades
.append(self
.trade_if_matching(
254 value_from
, portfolio
.Amount(base_currency
, 0),
255 currency
, only
=only
))
256 computed_trades
.append(self
.trade_if_matching(
257 portfolio
.Amount(base_currency
, 0), value_to
,
258 currency
, only
=only
))
260 computed_trades
.append(self
.trade_if_matching(
261 value_from
, value_to
,
262 currency
, only
=only
))
263 for matching
, trade
in computed_trades
:
265 self
.all
.append(trade
)
266 self
.market
.report
.log_trades(computed_trades
, only
)
268 def trade_if_matching(self
, value_from
, value_to
, currency
,
270 trade
= portfolio
.Trade(value_from
, value_to
, currency
,
272 matching
= only
is None or trade
.action
== only
273 return [matching
, trade
]
275 def prepare_orders(self
, only
=None, compute_value
="default"):
277 for trade
in self
.pending
:
278 if only
is None or trade
.action
== only
:
279 orders
.append(trade
.prepare_order(compute_value
=compute_value
))
280 self
.market
.report
.log_orders(orders
, only
, compute_value
)
282 def close_trades(self
):
283 for trade
in self
.all
:
286 def print_all_with_order(self
, ind
=""):
287 for trade
in self
.all
:
288 trade
.print_with_order(ind
=ind
)
290 def run_orders(self
):
291 orders
= self
.all_orders(state
="pending")
294 self
.market
.report
.log_stage("run_orders")
295 self
.market
.report
.log_orders(orders
)
297 def all_orders(self
, state
=None):
298 all_orders
= sum(map(lambda v
: v
.orders
, self
.all
), [])
302 return list(filter(lambda o
: o
.status
== state
, all_orders
))
304 def update_all_orders_status(self
):
305 for order
in self
.all_orders(state
="open"):
309 URL
= "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json"
313 report
= ReportStore(None)
316 def wait_for_recent(cls
, delta
=4):
317 cls
.get_cryptoportfolio()
318 while cls
.last_date
is None or datetime
.now() - cls
.last_date
> timedelta(delta
):
320 cls
.report
.print_log("Attempt to fetch up-to-date cryptoportfolio")
321 cls
.get_cryptoportfolio(refetch
=True)
324 def repartition(cls
, liquidity
="medium"):
325 cls
.get_cryptoportfolio()
326 liquidities
= cls
.liquidities
[liquidity
]
327 return liquidities
[cls
.last_date
]
330 def get_cryptoportfolio(cls
, refetch
=False):
331 if cls
.data
is not None and not refetch
:
334 r
= requests
.get(cls
.URL
)
335 cls
.report
.log_http_request(r
.request
.method
,
336 r
.request
.url
, r
.request
.body
, r
.request
.headers
, r
)
337 except Exception as e
:
338 cls
.report
.log_error("get_cryptoportfolio", exception
=e
)
341 cls
.data
= r
.json(parse_int
=D
, parse_float
=D
)
342 cls
.parse_cryptoportfolio()
343 except (JSONDecodeError
, SimpleJSONDecodeError
):
348 def parse_cryptoportfolio(cls
):
349 def filter_weights(weight_hash
):
350 if weight_hash
[1][0] == 0:
352 if weight_hash
[0] == "_row":
356 def clean_weights(i
):
357 def clean_weights_(h
):
358 if h
[0].endswith("s"):
359 return [h
[0][0:-1], (h
[1][i
], "short")]
361 return [h
[0], (h
[1][i
], "long")]
362 return clean_weights_
364 def parse_weights(portfolio_hash
):
365 weights_hash
= portfolio_hash
["weights"]
367 for i
in range(len(weights_hash
["_row"])):
368 date
= datetime
.strptime(weights_hash
["_row"][i
], "%Y-%m-%d")
369 weights
[date
] = dict(filter(
371 map(clean_weights(i
), weights_hash
.items())))
374 high_liquidity
= parse_weights(cls
.data
["portfolio_1"])
375 medium_liquidity
= parse_weights(cls
.data
["portfolio_2"])
378 "medium": medium_liquidity
,
379 "high": high_liquidity
,
381 cls
.last_date
= max(max(medium_liquidity
.keys()), max(high_liquidity
.keys()))