async def portfolio_allocations(folio_id, request): result = {"error": 0, "data": "", "message":""} language = request.__user__.get("language", "en") folio = await dao.findFolio(folio_id) if not folio: result["error"] = 402 result["message"] = _("402_NOT_EXIST", language) # "This portfolio does not exist." return result userid = request.__user__.get("referId", "") if int(userid) != folio.user_id: result["error"] = 408 result["data"] = {} result["message"] = _("408_NOT_VIEW", language) # "You do not have permission to view this page." return result allocations = json.loads(folio.allocations) if isinstance(folio.allocations, str) else json.loads(folio.allocations.decode()) allocations, init_assets = await calculate_weight(allocations) portfolio = {"allocations":[{"coin_name": allo['coin_name'], "weight": allo['weight'], "number": allo.get("number", ""), "coin_id": allo['coin_id'], "price": allo['price']} for allo in allocations], "folio_id": folio_id, "current_balance": init_assets } result['data'] = portfolio return result
async def getToken(self, request, kw): token = kw.get("token", "") language = toExistLanguage(kw.get("language", "en")) if token: user = await token2user(token) if user: request.__user__ = user vipEndDate = user.get("vipEndDate", "") read = hasVip(vipEndDate) request.__user__["read"] = read request.__user__["request_uuid"] = request_uuid() request.__user__["language"] = language else: if self._auth: r = {"error": 403, "data": {}, "message": _("403_LOGIN",language)} resp = to_response(r) return resp else: request.__user__ = {} request.__user__["language"] = language else: if self._auth: r = {"error": 403, "data": {}, "message": _("403_LOGIN",language)} resp = to_response(r) return resp else: request.__user__ = {} request.__user__["language"] = language return True
async def add_user_survey(request, *, option_one, option_two, option_three): result = {"error": 0, "data": "", "message": ""} user_id = request.__user__.get("referId", "") nickname = request.__user__.get("referName", "") head_image_url = request.__user__.get("headImageUrl", "") name = request.__user__.get("loginName", "") language = request.__user__.get("language", "en") count = await dao.findUserNumber(user_id) if count: result["error"] = 418 result["message"] = "The Account have been investigated!" else: option_one_val = choices["option_one"].get(int(option_one), 1) option_two_val = choices["option_two"].get(int(option_two), 1) option_three_val = choices["option_three"].get(int(option_three), 1) score = float(option_one_val) + float(option_two_val) + float( option_three_val) ratio = float( float(option_one_val) / 50 + float(option_two_val) / 10 + float(option_three_val) * 10) / 100.0 await dao.saveUser(user_id, name, nickname, head_image_url, option_one, option_two, option_three, score, ratio) result["message"] = _("0_ADD_SUCCESSFUL", language) # "Added successfully." return result
def wrapper(*args, **kw): try: return func(*args, **kw) except Exception as e: errMsg = getErrorMsg() error("options api error is: %s"%str(errMsg)) result = {"error": 500, "data": "", "message": _("500_SERVER_ERROR", kw.get("language","en"))} return result
async def request_frequency(self, request, kw): remote_ip = request.remote path_url = request.path language = toExistLanguage(kw.get("language", "en")) res = await frequency(remote_ip, path_url) if res: r = {"error": 416, "data": {}, "message": _("416_REQ_FREQUENT", language)} resp = to_response(r) return resp else: return True
async def portfolio_delete(folio_id, request): result = {"error": 0, "data": "", "message":""} language = request.__user__.get("language", "") folio = await dao.findFolio(folio_id) if not folio: result["error"] = 402 result["message"] = _("402_NOT_EXIST", language) #"This portfolio does not exist." return result userid = request.__user__.get("referId", "") if int(userid) != folio.user_id: result["error"] = 409 result["data"] = {} result["message"] = _("409_NOT_DELETE", language) #"You do not have permission to delete this portfolio." return result rows = await folio.remove() if rows == 1: await dao.delFolioPerformance(folio_id) result["message"] = _("0_DELETE_SUCCESSFUL", language) #"Deleted successfully." return result
async def portfolio_detail(folio_id, request, *, sort_type=""): result = {"error": 0, "data": "", "message":""} language = request.__user__.get("language", "") folio = await dao.findFolio(folio_id) if not folio: result["error"] = 402 result["message"] = _("402_NOT_EXIST", language) #"This portfolio does not exist." return result read = request.__user__.get("read", False) userid = request.__user__.get("referId", "") if int(userid) == folio.user_id: read = 1 history_value = history_dict.get(sort_type, "entire_history") if history_value != "hour_24_history": income_rate = round(float(folio[history_value]), 5) else: day_history = await calculate_portfolio(folio_id, folio=folio, re_cal=True, to_roi_rate=True) income_rate = round(float(day_history) * 100, 5) folio = folio.json() user_obj = await user_dao.findAllUser(folio["user_id"]) win_count, fail_count, sumCount = await dao.findFolioRate(history_value=history_value, args=[float(folio[history_value]),]) allocations = json.loads(folio["allocations"].decode()) succe_rate = round(float(win_count) * 100/float(sumCount), 5) allocations, init_assets = await calculate_weight(allocations) allocations = [{"coin_name": alloc.get("coin_name", ""), "number": alloc.get("number", ""), "weight": "%s%%"%str(round(float(alloc.get("weight", 0)) * 100, 3)), "rate":"%s%%"%str(round(float(alloc.get("rate",0)) * 100, 3)), "coin_id": alloc.get("coin_id", ""), "price": alloc.get("price", "")} for alloc in allocations] folio_rate = {"succe_rate": "%s%%"%str(succe_rate), "entire_history":"%s%%"%str(income_rate), "volatility":(folio["day_7_volatility"] if history_value=="day_7_history" else folio["volatility"]) if history_value!="hour_24_history" else "-", "max_drawdown":(folio["day_7_drawdown"] if history_value=="day_7_history" else folio["max_drawdown"]) if history_value!="hour_24_history" else "-", "hour_24_history":"%s%%"%str(folio["hour_24_history"]), "read_num": folio["read_num"], "current_balance": init_assets, "allocations":allocations if read else [], "rank":fail_count + 1, "folio_id": folio_id, "user_name": user_obj.nickname if user_obj else "", "head_image_url":user_obj.head_image_url if user_obj else "", "folio_name":folio["name"].rstrip(", ") if read else ""} result['data'] = folio_rate return result
def __init__(self, filename=None, lang="en"): json_data = default_dict self.help_dict = {} self.field_list = [] self.lang = lang fields = json_data['Fields'] for field_info in fields: field_name = field_info['Key'] field_label = _(field_info['Label'], self.lang) if 'Format' in field_info: fmt = field_info['Format'] else: fmt = "{0}" field = FieldInfo(field_name, field_label, fmt) self.field_list.append(field_name) self.help_dict[field_name] = field
async def get_coin_detail(coin_id, request): """ :param coin_id: :param request: :return: { "coin_name": "", "coin_id": "", "coin_url": "", "simple_name": "", "market_cap": "", "supply_pvolume": "", "trading_24_volume": "", "hours_1_index": "", "hours_24_index": "", "day_7_index": "", "price": "", "price_btc": "", "price_rate": "", "price_btc_rate": "", "trading_24_volume": "", "trading_24_btc_volume": "" } """ result = {"error": 0, "data": "", "message": ""} language = request.__user__.get("language", "en") if coin_id: coin_info = await dao.findCoinDetail(coin_id) else: coin_info = {} if coin_info: result["data"] = coin_info else: result["error"] = 411 result['data'] = {} result['message'] = _("411_COIN_NOT_EXIST", language) # "This coin does not exist." return result
def __call__(self, request): kw = None if self._has_var_kw_arg or self._has_named_kw_arg or self._required_kw_args or self._named_kw_args: if request.method in ('POST',"OPTIONS"): if not request.content_type: r = {"error": 404, "data": {}, "message": 'Missing Content-Type'} resp = to_response(r, method=request.method) return resp ct = request.content_type.lower() if ct.startswith('application/json'): params = yield from request.json() if not isinstance(params, dict): r = {"error": 404, "data": {}, "message": 'JSON Body must be object'} resp = to_response(r, method=request.method) return resp kw = params elif ct.startswith('application/x-www-form-urlencoded') or ct.startswith('multipart/form-data'): params = yield from request.post() kw = dict(**params) else: r = {"error": 404, "data": {}, "message": 'Unsupported Content-Type:%s' % request.content_type} resp = to_response(r, method=request.method) return resp if request.method == 'GET': qs = request.query_string if qs: kw = dict() for k, v in parse.parse_qs(qs, True).items(): kw[k] = v[0] if kw is None: kw = dict(**request.match_info) else: if not self._has_var_kw_arg and self._named_kw_args: copy = dict() for name in self._named_kw_args: if name in kw: copy[name] = kw[name] kw = copy for k, v in request.match_info.items(): if k in kw: error('Duplicate arg name in named arg and kw args: %s' % k) kw[k] = v if self._has_request_arg: kw['request'] = request language = toExistLanguage(kw.get("language", "en")) if self._required_kw_args: for name in self._required_kw_args: if not name in kw: r = {"error": 500, "data": {}, "message": _("500_SERVER_ERROR", language)} resp = to_response(r, method=request.method) return resp request_info('call with args: %s' % str(kw)) try: res = yield from self.request_frequency(request, kw) if res == True: resp = yield from self.getToken(request, kw) if resp == True: if "token" in kw: del kw["token"] if "language" in kw: del kw["language"] r = yield from self._func(**kw) return r else: return resp else: return res except Exception as e: errMsg = getErrorMsg() error("__call__ api error is: %s"%str(errMsg)) r = {"error": 500, "data": {}, "message": _("500_SERVER_ERROR", language)} resp = to_response(r, method=request.method) return resp
async def portfolio_ratios(port_folio=None, folio_id="", db=None, lang="en"): try: if not db: db = Connection.getInstance() if not port_folio: if folio_id: port_folio = await folios_dao.findFolio(folio_id) if not port_folio: return None else: return None helper = StatsHelper(lang=lang) proforma = await folios_dao.GetFolioPerformance(port_folio.id) if proforma: fts = proforma["pre_data"]["data"] now_data = [nowData["data"] for nowData in proforma["now_data"]] now_fts = [] for d in now_data: fts.extend(d) now_fts.extend(d) prof_fts = [perf["NetReturn"] for perf in now_fts] dates = [ datetime.fromtimestamp(p['EffectiveDate']) for p in now_fts ] fts_data = calculate_fts(prof_fts, dates) dates = [datetime.fromtimestamp(p['EffectiveDate']) for p in fts] prof_array = [perf["NetReturn"] for perf in fts] fts = Series(data=prof_array, index=dates, name=port_folio.name) T = len(fts) referenceData = await report_dao.findReferenceData('Risk Free Rate' ) if referenceData: rf = float(referenceData.data) * 0.01 else: rf = 0 stats_all = BasicStats(fts, risk_free=rf, folio_name=port_folio.name) roll_windows = windows[stats_all.freq[0]] roll_results = [] ratio_items = { "Cumulative Return": [], "Period volatility": { "volatility": "", "day_7_volatility": "" }, "Max Drawdown": { "max_drawdown": "", "day_7_drawdown": "" }, "entire_history": "", "day_7_history": "" } resultsAll = helper.help(stats_all) result_dict = dict(resultsAll) ratio_items["entire_history"] = fts_data[ "entire_history"] if fts_data else 0.0 ratio_items["day_7_history"] = fts_data[ "day_7_history"] if fts_data else 0.0 ratio_items["Period volatility"]["volatility"] = fts_data[ "total_volatility"] if fts_data else 0.0 ratio_items["Max Drawdown"]["max_drawdown"] = fts_data[ "total_max_drawdown"] if fts_data else 0.0 ratio_items["Cumulative Return"].append( result_dict.get(_("Cumulative Return", lang), "")) for index, w in enumerate(roll_windows): if T >= w: roll_fts = fts[-1 * w:] ratio_data = helper.help(BasicStats(roll_fts, risk_free=rf)) ratio_dict = dict(ratio_data) val = ratio_dict.get(_("Cumulative Return", lang), "") ratio_items["Cumulative Return"].append(val) if index == 0: ratio_items["Max Drawdown"][ "day_7_drawdown"] = fts_data[ "week_max_drawdown"] if fts_data else 0.0 ratio_items["Period volatility"][ "day_7_volatility"] = fts_data[ "week_volatility"] if fts_data else 0.0 roll_results.append([w, ratio_data]) await folios_dao.updateFolioHistory(port_folio.id, ratio_items) reportData = { "ResultsAll": resultsAll, "RollResults": roll_results, "Coin": { "Name": port_folio.name } } params = "ratios_%s" % lang await db.set_cache(port_folio.id, "portfolio", params, data=reportData, modify_at=port_folio.modify_at) else: roll_results = [] ratio_items = { "Cumulative Return": [], "Period volatility": { "volatility": "" }, "Max Drawdown": { "max_drawdown": "", "day_7_drawdown": "" } } resultsAll = helper.init_help() result_dict = dict(resultsAll) ratio_items["Period volatility"]["volatility"] = result_dict.get( "% Volatility", "") ratio_items["Max Drawdown"]["max_drawdown"] = result_dict.get( "Max Drawdown", "") ratio_items["Cumulative Return"].append( result_dict.get("Cumulative Return", "")) await folios_dao.updateFolioHistory(port_folio.id, ratio_items) reportData = { "ResultsAll": resultsAll, "RollResults": roll_results, "Coin": { "Name": port_folio.name } } except Exception as e: errMsg = getErrorMsg() error("portfolio_ratios exception is: %s, errMsg: %s" % (str(e), str(errMsg))) reportData = {} return reportData
async def add_coin_portfolios(request, portfolios): result = {"error": 0, "data": "", "message":""} user_id = request.__user__.get("referId", "") nickname = request.__user__.get("referName", "") head_image_url = request.__user__.get("headImgUrl", "") name = request.__user__.get("loginName", "") language = request.__user__.get("language", "en") status = request.__user__.get("status", 0) if int(status) != 1: result["error"] = 410 result["message"] = _("410_ACCOUNT_ACCESS", language) # "This account is not activated and has no access rights." return result res = await user_dao.saveUser(user_id, name, nickname, head_image_url, "", "", "", 0, status) if res != 1: res = await user_dao.findAllUser(user_id) if not res: res = await user_dao.saveUser(user_id, name, nickname, head_image_url, "", "", "", 0, status) if not res: result["error"] = 431 result["message"] = _("431_ACCOUNT_ACCESS", language) # "This account has no access rights." return result folio_name = "" allocations = [] if len(portfolios) > 10 or len(portfolios) < 1: result["error"] = 406 result["message"] = _("406_NUMBER_COINS", language) # "The number of coins has to be between 1 and 10." return result portfolios = sorted(portfolios, key=lambda folio : folio["weight"], reverse=True) all_weight = 0.0 coin_list = [] repeat = 0 usdt_w = 0 modify_at = time.time() for folio in portfolios: coin_name = folio.get("coin_name","") if coin_name not in coin_list: if coin_name: coin_list.append(coin_name) else: continue else: repeat = 1 break weight = folio.get("weight","") if not weight: continue weight = float(round(float(weight), 2)) if weight < 0: result["error"] = 417 result["message"] = _("417_WEIGHT_NOT_LESS_0", language) # "The weight should not be less than 0." return result coin_id = folio.get("coin_id","") all_weight += weight all_weight = float(round(all_weight,2)) if not coin_id: coin_obj = await coin_dao.findObjByName(coin_name) coin_id = coin_obj.id if coin_obj else "" else: coin_obj = await coin_dao.findCoin(coin_id) if not coin_obj: continue if coin_name.lower() in ("usdt", "tether"): usdt_w = weight if all_weight <= 1.0: folio_name += coin_obj.simple_name + ":" + str(int(float(weight) * 100)) + "% " price = coin_obj.price.replace(",", "").replace("$", "") net_return = float(round(100*(float(price) - float(coin_obj.pre_price.replace(",","").replace("$",""))) \ / float(coin_obj.pre_price.replace(",","").replace("$","")),5)) effective_date = float(int(modify_at)) number = round(float(1000000 * weight / float(price)), 3) allocations.append( {"coin_name": coin_obj.simple_name, "weight": weight, "coin_id": coin_id, "number": float(number), "rate": 0.0, "price": price, "Performance": [{"NetReturn": net_return, "EffectiveDate": effective_date}]}) if repeat: result["error"] = 407 result["message"] = _("407_DUPLICATION_COIN", language) # "The portfolio have the duplication of coin." return result if all_weight > 1.0: result["error"] = 415 result["message"] = _("415_WEIGHT_EXCEED", language) # "Coin weight cannot exceed 100%." return result if all_weight < 1: weight = float(round(float(100 - all_weight*100) / 100, 2)) if weight > 0.0: if usdt_w > 0.0: allocations_dict = {alloc["coin_name"].lower():alloc for alloc in allocations} alloc = allocations_dict.get("usdt",{}) if alloc: alloc["weight"] += weight alloc["weight"] = float(round(alloc["weight"], 2)) price = alloc["price"] number = round(float(1000000 * alloc["weight"] / float(price)), 3) alloc["number"] = float(number) alloc["rate"] = 0.0 allocations_dict["usdt"] = alloc allocations = list(allocations_dict.values()) else: coin_items = await coin_dao.findCoinByName("usdt") coin_id = coin_items[0].get("coin_id","") if coin_items else "" folio_name += "USDT:" + str(round(float(weight) * 100, 2)) + "% " coin_obj = await coin_dao.findCoin(coin_id) price = coin_obj.price.replace(",", "").replace("$", "") number = round(float(1000000 * weight / float(price)), 3) net_return = float(round(100 * (float(price) - float(coin_obj.pre_price.replace(",", "").replace("$", ""))) \ / float(coin_obj.pre_price.replace(",", "").replace("$", "")), 5)) effective_date = float(int(modify_at)) allocations.append({"coin_name": "USDT", "weight": weight, "coin_id": coin_id, "price": price, "number": float(number), "rate": 0.0, "Performance": [{"NetReturn": net_return, "EffectiveDate": effective_date}]}) count = await dao.findFolioNumber(where="user_id=?", args=[user_id]) if count >= 3: result["error"] = 401 result["message"] = _("401_MAXIMUM_THREE", language) # "The Maximum number of portfolio is three." else: port_folio, rows = await dao.saveFolio(user_id, folio_name, allocations, modify_at) if rows == 1: port_folio = await calculate_portfolio(port_folio.id, port_folio, is_create=True) result["data"] = {"folio_id": port_folio.id} result["message"] = _("0_ADD_SUCCESSFUL", language) # "Added successfully." return result
async def modify_coin_portfolios(request, folio_id, portfolios): result = {"error": 0, "data": {}, "message":""} language = request.__user__.get("language", "en") folio_name = "" allocations = [] port_folio = await dao.findFolio(folio_id) if not port_folio: result["error"] = 402 result["message"] = _("402_NOT_EXIST", language) # "This portfolio does not exist." return result userid = request.__user__.get("referId", "") if int(userid) != port_folio.user_id: result["error"] = 408 result["data"] = {} result["message"] = _("408_NOT_VIEW", language) # "You do not have permission to view this page." return result if len(portfolios) > 10 or len(portfolios) < 1: result["error"] = 406 result["message"] = _("406_NUMBER_COINS", language) # "The number of coins must be between 1 and 10." return result allo = json.loads(port_folio.allocations) if isinstance(port_folio.allocations, str) else json.loads(port_folio.allocations.decode()) allo, init_assets = await calculate_weight(allo) portfolios = sorted(portfolios, key=lambda folio: folio["weight"], reverse=True) all_weight = 0.0 coin_list = [] repeat = 0 usdt_w = 0 modify_at = time.time() for folio in portfolios: coin_name = folio.get("coin_name", "") if coin_name not in coin_list: if coin_name: coin_list.append(coin_name) else: continue else: repeat = 1 break weight = folio.get("weight", "") if not weight: continue weight = float(round(float(weight), 2)) if weight < 0: result["error"] = 417 result["message"] = _("417_WEIGHT_NOT_LESS_0", language) # "The weight should not be less than 0." return result coin_id = folio.get("coin_id", "") all_weight += float(weight) all_weight = float(round(all_weight, 2)) if not coin_id: coin_obj = await coin_dao.findObjByName(coin_name) coin_id = coin_obj.id if coin_obj else "" else: coin_obj = await coin_dao.findCoin(coin_id) if not coin_obj: continue if coin_name.lower() in ("usdt", "tether"): usdt_w = float(weight) if all_weight <= 1.0: folio_name += coin_obj.simple_name + ":" + str(int(float(weight) * 100)) + "% " net_return = float(round(100 * (float(coin_obj.price.replace(",", "").replace("$", "")) \ - float(coin_obj.pre_price.replace(",", "").replace("$", ""))) \ / float(coin_obj.pre_price.replace(",", "").replace("$", "")), 5)) effective_date = float(int(modify_at)) price = coin_obj.price.replace(",", "").replace("$", "") number = round(float(init_assets * weight / float(price)), 3) allocations.append( {"coin_name": coin_obj.simple_name, "weight": weight, "coin_id": coin_id, "number":number, "rate": 0.0, "price": price, "Performance": [{"NetReturn": net_return, "EffectiveDate": effective_date}]}) if repeat: result["error"] = 407 result["message"] = _("407_DUPLICATION_COIN", language) # "The portfolio have the duplication of coin." return result if all_weight > 1.0: result["error"] = 415 result["message"] = _("415_WEIGHT_EXCEED", language) # "Coin weight cannot exceed 100%." return result if all_weight < 1: weight = float(round(float(100 - all_weight*100) / 100, 2)) if weight > 0.0: if usdt_w > 0.0: allocations_dict = {alloc["coin_name"].lower():alloc for alloc in allocations} alloc = allocations_dict.get("usdt",{}) if alloc: alloc["weight"] += weight alloc["weight"] = float(round(alloc["weight"], 2)) price = alloc["price"] number = round(float(init_assets * alloc["weight"] / float(price)), 3) alloc["number"] = float(number) alloc["rate"] = 0.0 allocations_dict["usdt"] = alloc allocations = list(allocations_dict.values()) else: coin_items = await coin_dao.findCoinByName("usdt") coin_id = coin_items[0].get("coin_id","") if coin_items else "" folio_name += "USDT:" + str(round(float(weight) * 100, 2)) + "% " coin_obj = await coin_dao.findCoin(coin_id) price = coin_obj.price.replace(",", "").replace("$", "") number = round(float(init_assets * weight / float(price)), 3) net_return = float(round(100 * (float(coin_obj.price.replace(",", "").replace("$", "")) \ - float(coin_obj.pre_price.replace(",", "").replace("$", ""))) \ / float(coin_obj.pre_price.replace(",", "").replace("$", "")), 5)) effective_date = float(int(modify_at)) allocations.append({"coin_name": "USDT", "weight": weight, "coin_id": coin_id, "price": price, "number":number, "rate": 0.0, "Performance": [{"NetReturn": net_return, "EffectiveDate": effective_date}]}) folio = await calculate_portfolio(port_folio.id, port_folio, is_modify=True, folio_name=folio_name, new_allocations=allocations, modify_at=modify_at) if folio: result["data"] = {"folio_id": folio_id} result["message"] = _("0_MODIFY_SUCCESSFUL", language) # "Modified successfully." else: result["error"] = 402 result["message"] = _("402_NOT_EXIST", language) # "This portfolio does not exist." return result