def home(Req): if not Req.user.is_authenticated(): return login_page_with_redirect(Req) else: t = loader.get_template("finance.html") Dict = {} # it is not an actual information user_id = request.session["looking_user"] All = Accounts.objects.filter(user_id=user_id).order_by('-currency__ordering') BalancesOrders = OrdersMem.objects.filter(user_id=user_id, status="processing") OrdersBalances = {} for currency in BalancesOrders: if OrdersBalances.has_key(currency.currency1): OrdersBalances[currency.currency1] += currency.sum1 else: OrdersBalances[currency.currency1] = currency.sum1 ResAcc = [] for i in All: item = {} i.balance = format_numbers_strong(i.balance) item["balance"] = i.balance currency_id = i.currency.id item["currency"] = i.currency if OrdersBalances.has_key(currency_id): item["on_orders"] = format_numbers_strong(OrdersBalances[currency_id]) ResAcc.append(item) Dict["page_accounts"] = ResAcc return tmpl_context(Req, t, Dict)
def crypto_balances(request, CurrencyTitle): ###TODO add generator CurrencyInstance = Currency.objects.get( title = CurrencyTitle ) BalancesList = [] for item in Balances.objects.filter(currency = CurrencyInstance).exclude(account = "whole").order_by("-balance"): Cell = [ ] Cell.append(item.account) Cell.append(format_numbers_strong(item.balance)) BalancesList.append({"transes": Cell}) paginator = Paginator(BalancesList, 200) # Show 25 contacts per page page = request.GET.get('page', 1) try: BalancesListPage = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. BalancesListPage = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. BalancesListPage = paginator.page(paginator.num_pages) balance = Balances.objects.get(account = "whole", currency = CurrencyInstance) Dict = {"trans_page_title": _(u"Балансы {currency} - общий {balance}").format(currency=CurrencyTitle, balance=format_numbers_strong(balance.balance) ), "paging": True, "Trans" : BalancesListPage, "TransList":BalancesListPage.object_list, "TransTitle": [{"value":_(u"Адрес")},{"value":_(u"Баланс")} ] } tmpl = loader.get_template("common_trans_page.html") return http_tmpl_context(request, tmpl, Dict)
def home(Req): if not Req.user.is_authenticated(): return login_page_with_redirect(Req) else: t = loader.get_template("finance.html") Dict = {} All = Accounts.objects.filter(user=Req.user).order_by("-currency__ordering") BalancesOrders = ( OrdersMem.objects.filter(user=Req.user.id, status="processing") .values("currency1") .annotate(balances=Sum("sum1")) ) OrdersBalances = {} for currency in BalancesOrders: OrdersBalances[currency["currency1"]] = currency["balances"] ResAcc = [] for i in All: item = {} i.balance = format_numbers_strong(i.balance) item["balance"] = i.balance currency_id = i.currency.id item["currency"] = i.currency if OrdersBalances.has_key(currency_id): item["on_orders"] = format_numbers_strong(OrdersBalances[currency_id]) ResAcc.append(item) Dict["page_accounts"] = ResAcc return tmpl_context(Req, t, Dict)
def client_orders(Req, User_id, Title): Dict = {} Current = None try: Current = TradePairs.objects.get(url_title=Title) except: return json_false500(Req) Dict["auth"] = True MyOrders = Orders.objects.raw( "SELECT * FROM main_orders WHERE user_id=%i AND ( \ (currency1_id=%i AND currency2_id=%i ) OR \ (currency2_id=%i AND currency1_id=%i )\ ) AND status='processing' ORDER BY id DESC" % ( User_id, Current.currency_from.id, Current.currency_on.id, Current.currency_from.id, Current.currency_on.id, )) MyOrdersList = [] c = getcontext() c.prec = settings.TRANS_PREC for i in MyOrders: MyOrdersDict = {} MyOrdersDict["pub_date"] = formats.date_format(i.pub_date, "DATETIME_FORMAT") MyOrdersDict["id"] = i.id MyOrdersDict["sum2"] = str(i.sum2) MyOrdersDict["sum1"] = str(i.sum1) if i.currency1 == Current.currency_on: MyOrdersDict["type"] = "sell" Number = i.sum2 / i.sum1 MyOrdersDict["price"] = format_numbers10(i.price) MyOrdersDict["amnt_trade"] = format_numbers10(i.sum1) MyOrdersDict["amnt_base"] = format_numbers10(i.sum2) else: MyOrdersDict["type"] = "buy" Number = i.sum1 / i.sum2 MyOrdersDict["price"] = format_numbers10(i.price) MyOrdersDict["amnt_base"] = format_numbers10(i.sum1) MyOrdersDict["amnt_trade"] = format_numbers10(i.sum2) MyOrdersList.append(MyOrdersDict) balance_sell = Accounts.objects.get(user_id=User_id, currency=Current.currency_on) balance_buy = Accounts.objects.get(user_id=User_id, currency=Current.currency_from) Dict["balance_buy"] = format_numbers_strong(balance_buy.balance) Dict["balance_sell"] = format_numbers_strong(balance_sell.balance) Dict["your_open_orders"] = MyOrdersList RespJ = json.JSONEncoder().encode(Dict) return RespJ
def make_auto_trade(Order, TradePair, Price, Currency1, Sum1, Currency2, Sum2): List = None ##if we sell if int(TradePair.currency_on.id) == int(Currency1.id): Query = "SELECT * FROM main_orders WHERE currency1_id=%i AND currency2_id=%i \ AND status='processing' AND price >= %s \ AND user_id!=%i ORDER BY price DESC" % ( Currency2.id, Currency1.id, format_numbers_strong(Price), Order.user.id) else: Query = "SELECT * FROM main_orders WHERE currency1_id=%i AND currency2_id=%i \ AND status='processing' AND price <= %s \ AND user_id!=%i ORDER BY price " % ( Currency2.id, Currency1.id, format_numbers_strong(Price), Order.user.id) List = Orders.objects.raw(Query) ##work on first case CommissionSell = Accounts.objects.get(user_id=settings.COMISSION_USER, currency=Currency1) ComnissionBuy = Accounts.objects.get(user_id=settings.COMISSION_USER, currency=Currency2) AccumSumToSell = Sum1 AccumSum2Buy = Sum2 AccountBuyer = get_account(Order.user, Currency2) UserDeals = [Order.user.id] for item in List: (AccumSum2Buy, AccumSumToSell) = process_order(AccountBuyer, ComnissionBuy, AccumSum2Buy, AccumSumToSell, item, Order, TradePair, CommissionSell) UserDeals.append([item.user_id]) if AccumSum2Buy > 0.00000001: continue else: break ResultSum = finish_create_order(TradePair, AccumSum2Buy, AccumSumToSell, Order) Order.sum1 = AccumSumToSell if ResultSum > 0.00000001: Order.sum2 = ResultSum else: Order.sum2 = 0 Order.status = "processed" ##if order has rest of funds return all to account if AccumSumToSell > 0 and Order.sum2 == 0 and Order.status == "processed": return_rest2acc(Order, AccumSumToSell) Order.sum1 = 0 Order.save() return { "start_sum": Sum2, "last_sum": ResultSum, "users_bothered": UserDeals }
def client_orders(Req, User_id, Title ): Dict = {} Current = None try: Current = TradePairs.objects.get(url_title = Title) except : return json_false500(Req) Dict["auth"] = True MyOrders = Orders.objects.raw("SELECT * FROM main_orders WHERE user_id=%i AND ( \ (currency1_id=%i AND currency2_id=%i ) OR \ (currency2_id=%i AND currency1_id=%i )\ ) AND status='processing' ORDER BY id DESC" % (User_id, Current.currency_from.id, Current.currency_on.id, Current.currency_from.id, Current.currency_on.id, ) ) MyOrdersList = [] c = getcontext() c.prec = settings.TRANS_PREC for i in MyOrders: MyOrdersDict = {} MyOrdersDict["pub_date"] = formats.date_format(i.pub_date, "DATETIME_FORMAT") MyOrdersDict["id"] = i.id MyOrdersDict["sum2"] = str(i.sum2) MyOrdersDict["sum1"] = str(i.sum1) if i.currency1 == Current.currency_on : MyOrdersDict["type"] = "sell" Number = i.sum2 / i.sum1 MyOrdersDict["price"] = format_numbers10(i.price) MyOrdersDict["amnt_trade"] = format_numbers10(i.sum1) MyOrdersDict["amnt_base"] = format_numbers10(i.sum2) else: MyOrdersDict["type"] = "buy" Number = i.sum1/ i.sum2 MyOrdersDict["price"] = format_numbers10(i.price) MyOrdersDict["amnt_base"] = format_numbers10(i.sum1) MyOrdersDict["amnt_trade"] = format_numbers10(i.sum2) MyOrdersList.append(MyOrdersDict) balance_sell = Accounts.objects.get(user_id = User_id, currency = Current.currency_on ) balance_buy = Accounts.objects.get(user_id = User_id, currency = Current.currency_from ) Dict["balance_buy"] = format_numbers_strong(balance_buy.balance ) Dict["balance_sell"] = format_numbers_strong(balance_sell.balance ) Dict["your_open_orders"] = MyOrdersList RespJ = json.JSONEncoder().encode(Dict) return RespJ
def make_auto_trade(Order, TradePair, Price, Currency1, Sum1, Currency2, Sum2): List = None ##if we sell if int(TradePair.currency_on.id) == int(Currency1.id): Query = "SELECT * FROM main_orders WHERE currency1_id=%i AND currency2_id=%i \ AND status='processing' AND price >= %s \ AND user_id!=%i ORDER BY price DESC" % ( Currency2.id, Currency1.id, format_numbers_strong( Price ), Order.user.id) else : Query = "SELECT * FROM main_orders WHERE currency1_id=%i AND currency2_id=%i \ AND status='processing' AND price <= %s \ AND user_id!=%i ORDER BY price " % (Currency2.id, Currency1.id, format_numbers_strong( Price ), Order.user.id ) List = Orders.objects.raw(Query) ##work on first case CommissionSell = Accounts.objects.get(user_id = settings.COMISSION_USER, currency = Currency1) ComnissionBuy = Accounts.objects.get(user_id = settings.COMISSION_USER, currency = Currency2) AccumSumToSell = Sum1 AccumSum2Buy = Sum2 AccountBuyer = get_account(Order.user, Currency2) UserDeals = [Order.user.id] for item in List: (AccumSum2Buy, AccumSumToSell ) = process_order(AccountBuyer, ComnissionBuy, AccumSum2Buy, AccumSumToSell, item, Order, TradePair, CommissionSell ) UserDeals.append([item.user_id]) if AccumSum2Buy>0.00000001 : continue else : break ResultSum = finish_create_order(TradePair, AccumSum2Buy, AccumSumToSell, Order) Order.sum1 = AccumSumToSell if ResultSum>0.00000001: Order.sum2 = ResultSum else: Order.sum2 = 0 Order.status = "processed" ##if order has rest of funds return all to account if AccumSumToSell>0 and Order.sum2 == 0 and Order.status == "processed": return_rest2acc(Order, AccumSumToSell) Order.sum1 = 0 Order.save() return {"start_sum":Sum2 , "last_sum": ResultSum, "users_bothered" : UserDeals }
def setup_trades_pairs(Title, Dict=None): if Dict is None: Dict = {} ListCurrency = [] Current = TradePairs.objects.get(url_title=Title) List = list(TradePairs.objects.filter(status="processing").order_by("ordering")) Base = List[0].currency_from.long_title # ListCurrency.append( {"is_title": True, "title" : Base } ) for item in List: if item.currency_from.long_title != Base: # ListCurrency.append({"is_title": True, "title" : item.currency_from.long_title}) Base = item.currency_from.long_title try: Price = VolatileConsts.objects.get(Name=item.url_title + "_top_price") item.top_price = Price.Value except: item.top_price = "None" ListCurrency.append(item) Dict["Currency1"] = Current.currency_from Dict["min_deal"] = format_numbers_strong(Current.min_trade_base) Dict["Currency"] = Current.currency_on Dict["CurrencyTrade"] = ListCurrency return Dict
def crypto_balances(request, CurrencyTitle): ###TODO add generator CurrencyInstance = Currency.objects.get(title=CurrencyTitle) BalancesList = [] for item in Balances.objects.filter(currency=CurrencyInstance).exclude(account="whole").order_by("-balance"): Cell = [] Cell.append(item.account) Cell.append(format_numbers_strong(item.balance)) BalancesList.append({"transes": Cell}) paginator = Paginator(BalancesList, 200) # Show 25 contacts per page page = request.GET.get('page', 1) try: BalancesListPage = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. BalancesListPage = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. BalancesListPage = paginator.page(paginator.num_pages) balance = Balances.objects.get(account="whole", currency=CurrencyInstance) Dict = {"trans_page_title": _(u"Балансы {currency} - общий {balance}").format(currency=CurrencyTitle, balance=format_numbers_strong( balance.balance)), "paging": True, "Trans": BalancesListPage, "TransList": BalancesListPage.object_list, "TransTitle": [{"value": _(u"Адрес")}, {"value": _(u"Баланс")}] } tmpl = loader.get_template("common_trans_page.html") return http_tmpl_context(request, tmpl, Dict)
def process_in_crypto(Time, CurrencyTitle): Crypton = CryptoAccount(CurrencyTitle, "trade_stock") List = Crypton.listtransactions() user_system = User.objects.get(id=1) CurrencyInstance = Currency.objects.get(title=CurrencyTitle) getcontext().prec = crypton.settings.TRANS_PREC for trans in List: Txid = trans["txid"] # print "receive transactions %s" % (str(trans)) if trans.has_key("blocktime") and trans["blocktime"] < Time: # print "old transactions "; # print "blocktime is %i " % trans["blocktime"] continue #if trans["amount"]<0.0001: # continue if trans["category"] == "receive": Account = None Trans = None New = False Decimal = format_numbers_strong(trans["amount"]) try: Account = Accounts.objects.get(reference=trans["address"]) Trans = CryptoTransfers.objects.get(crypto_txid=Txid, currency=CurrencyInstance) except Accounts.DoesNotExist: # notify_admin_withdraw(u"unrecognized crypto incoming to %s %s %s" % (trans["address"], # Decimal, # CurrencyTitle # ) ) continue except CryptoTransfers.DoesNotExist: Trans = CryptoTransfers(crypto_txid=Txid, status="created", amnt=Decimal, currency=CurrencyInstance, account=trans["address"], user=Account.user, confirms=0) Trans.save() print "in one trans to our accounts" print "#%i receive %s to %s amount of %s" % (Trans.id, Txid, trans["address"], trans['amount'] ) # print "confirmations %i" % (trans["confirmations"] ) # print "this trans is %s" % (Trans.status) if (Trans.status == "processing" or Trans.status == "created" ) and trans["confirmations"] > \ CryptoSettings[CurrencyTitle]["min_confirmation"]: print "processing it %s" % (str(trans)) Trans.confirms = int(trans["confirmations"]) Trans.status = "processing" Trans.save() # print "in in" crypton_in(Trans, user_system) if Trans.status == "processing" or Trans.status == "created": # print "update confirmations" Trans.status = "processing" Trans.confirms = int(trans["confirmations"]) Trans.save()
def fields4sign(self): List = [] for i in ('phone', 'debit_credit', 'status', 'user', 'comission', 'amnt', 'description'): Val = getattr(self, i) if i in ('comission', 'amnt'): List.append(format_numbers_strong(Val)) else: List.append(str(Val)) return ",".join(List)
def ask(Req, UrlTitle): CurrentTradePair = TradePairs.objects.get(url_title=UrlTitle) SumList = [] Amount = Decimal("0") TempSum = Decimal('0') try: Amount = Decimal(Req.REQUEST.get("amount", None)) Query = "SELECT * FROM main_orders WHERE currency1_id=%i AND currency2_id=%i \ AND status='processing' \ AND user_id!=%i ORDER BY price DESC" % ( CurrentTradePair.currency_on.id, CurrentTradePair.currency_from.id, Req.user.id) List = Orders.objects.raw(Query) for item in List: if Amount > item.sum1: Amount -= item.sum1 TempSum += item.sum1 SumList.append({"sum": item.sum1, "price": item.price}) else: TempSum += Amount SumList.append({"sum": Amount, "price": item.price}) break except: Response = HttpResponse( '{"status":false, "description":"amount is incorrect"}') Response['Content-Type'] = 'application/json' return Response #format_numbers_strong(balance_buy.balance ) AvaragePrice = Decimal("0") BuySum = Decimal("0") for item in SumList: BuySum += item['sum'] AvaragePrice += ((item['sum'] / TempSum) * item['price']) Dict = { "buy_sum": format_numbers_strong(BuySum), "price": format_numbers_strong(AvaragePrice), "status": True } RespJ = json.JSONEncoder().encode(Dict) return cached_json_object(RespJ)
def ask(Req, UrlTitle): CurrentTradePair = TradePairs.objects.get(url_title = UrlTitle) SumList = [] Amount = Decimal("0") TempSum = Decimal('0') try: Amount = Decimal( Req.REQUEST.get("amount", None) ) Query = "SELECT * FROM main_orders WHERE currency1_id=%i AND currency2_id=%i \ AND status='processing' \ AND user_id!=%i ORDER BY price DESC" % ( CurrentTradePair.currency_on.id, CurrentTradePair.currency_from.id, Req.user.id) List = Orders.objects.raw(Query) for item in List: if Amount > item.sum1 : Amount -= item.sum1 TempSum += item.sum1 SumList.append({"sum":item.sum1,"price":item.price}) else: TempSum += Amount SumList.append({"sum":Amount,"price":item.price}) break except : Response = HttpResponse('{"status":false, "description":"amount is incorrect"}') Response['Content-Type'] = 'application/json' return Response #format_numbers_strong(balance_buy.balance ) AvaragePrice = Decimal("0") BuySum = Decimal("0") for item in SumList: BuySum += item['sum'] AvaragePrice += ((item['sum']/TempSum)*item['price'] ) Dict = {"buy_sum": format_numbers_strong(BuySum), "price": format_numbers_strong(AvaragePrice), "status":True } RespJ = json.JSONEncoder().encode(Dict) return cached_json_object(RespJ)
def trans(Req): t = loader.get_template("finance_trans.html") Dict = {} ListAccounts = [] DictAccounts = {} for i in Accounts.objects.filter(user=Req.user): ListAccounts.append(str(i.id)) DictAccounts[i.id] = 1 AccountsStr = ",".join(ListAccounts) Query = ( "SELECT * FROM main_trans WHERE 1 \ AND status in ('payin','deposit','withdraw','deal','order_cancel','comission','bonus','deal_return')\ AND ( user1_id IN (%s) OR user2_id IN (%s) ) ORDER BY id DESC " % (AccountsStr, AccountsStr) ) List = Trans.objects.raw(Query) All = [] for item in List: new_item = {} new_item["description"] = generate_description(DictAccounts, item) new_item["amnt"] = format_numbers_strong(item.amnt) new_item["currency"] = item.currency.title new_item["ts"] = formats.date_format(item.pub_date, "DATETIME_FORMAT") new_item["id"] = item.id new_item["in"] = False if DictAccounts.has_key(item.user2_id): new_item["in"] = True All.append(new_item) page = Req.GET.get("page", 1) PageObject = my_cached_paging("user_id_trans" + str(Req.user.id), Trans, page, All) Dict["trans_list"] = PageObject.object_list Dict["paging"] = PageObject return tmpl_context(Req, t, Dict)
def trans(Req): t = loader.get_template("finance_trans.html") Dict = {} user_id = Req.user.id ListAccounts = [] DictAccounts = {} for i in Accounts.objects.filter(user_id=user_id): ListAccounts.append(str(i.id)) DictAccounts[i.id] = 1 AccountsStr = ",".join(ListAccounts) Query = "SELECT * FROM main_trans WHERE 1 \ AND status in ('payin','deposit','withdraw','deal','order_cancel','comission','bonus','deal_return')\ AND ( user1_id IN (%s) OR user2_id IN (%s) ) ORDER BY id DESC " % ( AccountsStr, AccountsStr) List = Trans.objects.raw(Query) All = [] for item in List: new_item = {} new_item["description"] = generate_description(DictAccounts, item) new_item["amnt"] = format_numbers_strong(item.amnt) new_item["currency"] = item.currency.title new_item["ts"] = int((item.pub_date - datetime.datetime(1970,1,1)).total_seconds()) new_item["id"] = item.id new_item["in"] = False if DictAccounts.has_key(item.user2_id): new_item["in"] = True All.append(new_item) page = Req.GET.get('page', 1) PageObject = my_cached_paging("user_id_trans" + str(user_id), Trans, page, All) Dict["trans_list"] = PageObject.object_list Dict["paging"] = PageObject return tmpl_context(Req, t, Dict)
def whole_balance(request): CurList = Currency.objects.all() UAH = Currency.objects.get(id = 1) CurrencyConsist = [] CurrencyLocalBalance = [] CurrencyFor = [] SaldoCor = [] cursor = connection.cursor() ## 346 mistake object #{% for item in currency_consist %} #<p>Сальдо {{ item.currency }} : {{ item.sum }} </p> #{% endfor %} MinesDec = Decimal("-1") for cur in CurList: Id = cur.id cursor.execute("SELECT sum(balance) FROM main_accounts WHERE currency_id='%s' \ AND user_id not in (346, 31) AND abs(balance)>0.000000001 ", [Id]) s = cursor.fetchone()*1 if s == (None, ) : s = Decimal("0.0") CurrencyConsist.append({ "currency": cur.title, "sum": format_numbers_strong(s) }) ##get balances of crypto without uah for cur in Accounts.objects.filter(user_id = settings.CRYPTO_USER).exclude(currency_id = 1): if cur.balance is None: cur.balance = Decimal("0") CurrencyLocalBalance.append({"currency": cur.currency.title, "sum": format_numbers_strong(cur.balance*MinesDec) }) P24User = User.objects.get(username = p24.str_class_name() ) P24 = Accounts.objects.get(user = P24User, currency_id = 1) LiqPayU = User.objects.get(username = liqpay.str_class_name() ) LiqPay = Accounts.objects.get(user = LiqPayU, currency_id = 1) TradePair = TradePairs.objects.get(url_title = "p2p_transfers" ) CurrencyLocalBalance.append({"currency": "UAH", "sum": format_numbers_strong( MinesDec*(TradePair.transit_from.balance + LiqPay.balance + P24.balance) ) }) CurrencyFor = [] Balances = {} for cur in CurList: if cur.id != 1: try: Crypto = CryptoAccount(cur.title) DecSum = Decimal(Crypto.getbalance() ) except : DecSum = Decimal("0.0") Sum = format_numbers_strong( DecSum ) Balances[ cur.title ] = DecSum CurrencyFor.append({"currency": cur.title, "sum": Sum }) D = p24() BalanceUAH = Decimal(D.balance()) Balances[ "UAH" ] = BalanceUAH CurrencyFor.append({"currency": "UAH", "sum": format_numbers_strong( BalanceUAH ) }) ComisId = int(settings.COMISSION_USER) for cur in CurList: Id = int(cur.id) if cur.id != 1: cursor.execute("SELECT sum(balance) FROM main_accounts WHERE currency_id=%i\ AND user_id not in (346, %i, 31 ) AND balance>0 " % ( Id,ComisId ), [] ) (s,) = cursor.fetchone()*1 if s == None : s = Decimal("0.0") SaldoCor.append({ "currency": cur.title, "sum": format_numbers_strong( Balances[cur.title] - s ) }) cursor.execute("SELECT sum(balance) FROM main_accounts WHERE currency_id=1\ AND user_id not in (346, %i, 12,31 ) AND balance>0 " % ( ComisId ), []) (s, ) = cursor.fetchone()*1 SaldoCor.append({ "currency": "UAH", "sum": format_numbers_strong( Balances["UAH"] - s ) }) return render_to_response('admin/main/whole_balance.html', {'currency_consist': CurrencyConsist, "currency_local_balance":CurrencyLocalBalance, "currency_balance":CurrencyFor, "saldo": SaldoCor }, context_instance = RequestContext(request) )