Example #1
0
 def dispatch(self, request, *args, **kwargs):
     self.goal = get_object_or_404(Goal, pk=kwargs["pk"])
     self.transaction = Transaction(account=self.goal,
                                    amount=self.goal.allocation,
                                    type=TRANSACTION_TYPE_ALLOCATION,
                                    status=Transaction.STATUS_PENDING,
                                    created=now().today())
     response = super(GoalRebalance, self).dispatch(request, *args,
                                                    **kwargs)
     return response
Example #2
0
def autoreward_lesson(lesson):
    if not lesson.contest_id:
        return
    upsolving = is_upsolving(lesson.contest_id)
    rules = [Rule(upsolving, rule) for rule in lesson.autorewards.split("\n")]
    runs = run_contests_cmd(lesson.contest_id, "dump-filtered-runs",
                            "status==OK", "0", "-1").split('\n')
    for s in runs:
        if not s:
            continue
        info = s.split(';')
        user_id, prob = int(info[10]), info[18]
        if not Autoreward.objects.filter(
                user__id=user_id, prob=prob, lesson=lesson).exists():
            score = 0
            for rule in rules:
                if rule.appliable(prob):
                    score += rule.score
                    if not rule.add:
                        break
            r = Autoreward()
            r.user = EjudgeAuthBackend().get_user(user_id)
            r.prob = prob
            r.lesson = lesson
            r.save()
            if score > 0:
                r.user.bonuses += score
                r.user.save()
                lesson.bank.bonuses -= score
                tr = Transaction()
                tr.sender = lesson.bank
                tr.receiver = r.user
                tr.amount = score
                tr.save()
    lesson.bank.save()
 def put(self, request):
     body = json.loads(request.body)
     transaction = Transaction()
     if 'currency' in body:
         transaction.choice_currency = body.get('currency')
     transaction.transaction_from = FinancialNode.objects.filter(
         id=int(body['transaction_from'])).first()
     transaction.transaction_to = FinancialNode.objects.filter(
         id=int(body['transaction_to'])).first()
     transaction.amount = int(body['amount'])
     transaction.data_from = datetime.strptime(body['date'],
                                               '%d.%m.%Y').date()
     transaction.user = request.user
     transaction.save()
     body['id'] = transaction.id
     body['transaction_from'] = transaction.transaction_from.name
     body['transaction_to'] = transaction.transaction_to.name
     return JsonResponse({'ok': True, 'body': body})
Example #4
0
    def handle(self, *args, **kwargs):
        self.stdout.write("Importing data...")

        csvRows = []

        csvFileObj = open(filename)
        readerObj = csv.reader(csvFileObj)

        for row in readerObj:
            if readerObj.line_num == 1:
                continue
            csvRows.append(row)

        csvFileObj.close()

        for item in csvRows:
            theDate = item[0].split(' ')
            date = datetime.date(year=int(theDate[2]), month=int(
                theDate[1]), day=int(theDate[0]))
            theType = item[1]
            name = item[2]
            account = item[3]
            deposit = item[4].strip()
            withdrawal = item[5].strip()

            if deposit == "":
                status = 'W'
                if withdrawal == "":
                    amount = 0
                else:
                    amount = int(withdrawal)
            else:
                status = 'D'
                if deposit == '':
                    amount = 0
                else:
                    amount = int(deposit)

            trans = Transaction(
                name=name, amount=amount, payment_type=theType,
                account=account, status=status, date=date)
            trans.save()

        self.stdout.write(f"{Transaction.objects.count()} Data Processed")
Example #5
0
async def verify(ctx):
    if await channelcheck(server_list, ctx):
        return

    async with ctx.channel.typing():

        for address in address_holder:
            if address.user_id == ctx.author.id:
                r = requests.get(
                    f"http://45.33.60.42/bank_transactions?format=json&limit=1&block__sender={address.address}&recipient={bot_wallet}"
                )  # sender and receiver logic needed as well as a user DB
                info = r.json()
                if any(info["results"]):
                    query = User(DiscordID=int(ctx.author.id),
                                 Address=address.address)
                    query.save()
                    newTX = Transaction(Type="DEPOSIT",
                                        TxID=info["results"][0]["id"],
                                        Amount=int(
                                            info["results"][0]['amount']))
                    newTX.save()
                    embed = discord.Embed(
                        title='Success!',
                        description=
                        f"Address `{address.address}` succesfully associated with {ctx.author.mention}",
                        color=bot_color)
                    await ctx.send(embed=embed)
                    address_holder.remove(address)
                else:
                    embed = discord.Embed(
                        title='No Transaction',
                        description=
                        f"No transaction detected from `{address.address}`")
                    await ctx.send(embed=embed)
                return
        embed = discord.Embed(
            title="No Address",
            description=
            f"No address to verify. Did you make sure to use `{bot_prefix}register ACCOUNT_NUMBER`?",
            color=bot_color)
        await ctx.send(embed=embed)
Example #6
0
def prizes(req):
    if not req.user.is_authenticated:
        raise Http404()
    if req.POST.get('action') == 'purchase':
        try:
            prize = Prize.objects.get(id=req.POST.get('prize'))
            if prize.stock <= 0:
                raise ValueError("Not enough stock")
            if prize.cost > req.user.bonuses:
                raise ValueError("Too expensive")
            purchase = Purchase()
            purchase.user = req.user
            purchase.prize = prize
            purchase.code = ''.join(
                random.choice("ABCDEFGHKMNPQRSTUVWXYZ23456789")
                for _ in range(8))
            purchase.status = Purchase.PAYED
            purchase.save()
            transaction = Transaction()
            transaction.sender = req.user
            transaction.amount = prize.cost
            transaction.save()
            req.user.bonuses -= prize.cost
            req.user.save()
            prize.stock -= 1
            prize.save()
            return redirect('/')
        except:
            raise Http404()
    return render(req,
                  'prizes.html',
                  context=dict(prizes=Prize.objects.filter(
                      stock__gt=0).order_by('cost').all()))
Example #7
0
 def add_recurring_charges(self, r_file, user, month):
     with open(r_file, "r", encoding="utf-8") as rec_file:
         for line in rec_file:
             line = line.rstrip()
             if line != "":
                 parts = line.split("\t")
                 if len(parts) != 3:
                     raise Exception(_("Recurring charges file is not valid"))
                 subject = parts[0]
                 amount = float(parts[1].replace(",", "."))
                 category = Category.objects.get(name=parts[2].lower().capitalize())
                 tg_month = month.month + settings.NEW_MONTH_INTERVAL
                 tg_year = month.year
                 if tg_month < 1:
                     tg_month += 12
                     tg_year -= 1
                 group = TransactionGroup(date_t="%04d-%02d-%02d" %
                                                 (tg_year, tg_month,
                                                  settings.NEW_MONTH_DAY), month=month, ignore_week_filters=True)
                 group.save()
                 transaction = Transaction(subject=subject, amount=amount, category=category, group=group)
                 transaction.save()
Example #8
0
def give_bonuses(modeladmin, request, queryset):
    bonuses = int(request.POST['bonuses'])
    for user in queryset:
        user.bonuses += bonuses
        user.save()
        request.user.bonuses -= bonuses
        tr = Transaction()
        tr.sender = request.user
        tr.receiver = user
        tr.amount = bonuses
        tr.save()
    request.user.save()
Example #9
0
def checkout(request):
    if request.method == 'POST':
        cart = Cart.objects.filter(customer_id=Account.objects.get(
            user=request.user))
        price = 0
        for item in cart:
            product = Product.objects.get(id=item.product_id)
            product.quantity -= 1
            product.save()
            price += product.price
            print(price)
            transaction = Transaction(accountID=product.sellerID,
                                      changeAmount=(product.price))
            transaction.save()
        transaction.save()
        currentAccount = Account.objects.get(user=request.user)
        currentAccount.balance -= price
        currentAccount.save()
        cart.delete()
        transaction = Transaction(
            accountID=Account.objects.get(user=request.user),
            changeAmount=(-price))
        transaction.save()
        return HttpResponse("Items Purchased")
Example #10
0
    def post(self, request, *args, **kwargs):
        payload = ujson.loads(request.body.decode('utf8'))
        goal = get_object_or_404(Goal,
                                 pk=kwargs["pk"],
                                 account__primary_owner=self.client)
        new_transaction = Transaction()
        new_transaction.account = goal
        new_transaction.from_account = None
        new_transaction.to_account = None
        new_transaction.type = Transaction.REASON_WITHDRAWAL
        new_transaction.amount = payload["amount"]
        new_transaction.save()

        nt_return = {
            "transactionId": new_transaction.pk,
            "account": new_transaction.account.pk,
            "type": new_transaction.type,
            "amount": new_transaction.amount
        }

        return HttpResponse(ujson.dumps(nt_return),
                            content_type="application/json")
Example #11
0
def fifth(request):
    customers = Customer.objects.all()

    if request.method == "POST":
        sender = request.POST.get("sender")
        receiver = request.POST.get("receiver")
        Amount = request.POST.get("Amount")

        status = False

        if int(sender) > 0 and int(receiver) > 0:
            sender_acc = Customer.objects.get(cid=sender)
            receiver_acc = Customer.objects.get(cid=receiver)
            if float(sender_acc.balance) > float(Amount):
                sender_acc.balance = float(sender_acc.balance) - float(Amount)
                receiver_acc.balance = float(
                    receiver_acc.balance) + float(Amount)
                sender_acc.save()
                receiver_acc.save()
                status = True
                t = Transaction(sender_acc=sender_acc,
                                receiver_acc=receiver_acc,
                                Amount=Amount,
                                status=status,
                                date=datetime.now())
                t.save()
                r = 1
                return redirect('/AllTransactions/1')

            else:
                messages.info(request, 'Insufficient Balance ')
                t = Transaction(sender_acc=sender_acc,
                                receiver_acc=receiver_acc,
                                Amount=Amount,
                                status=status,
                                date=datetime.now())
                t.save()
                return redirect("transfer", customer_id=int(sender))

        else:
            messages.warning(request, 'Enter Correct users ')

    return render(request, "fifth.html", context={'customers': customers})
Example #12
0
def make_declined(modeladmin, request, queryset):
    for purchase in queryset.all():
        purchase.user.bonuses += purchase.prize.cost
        purchase.user.save()
        purchase.prize.stock += 1
        purchase.prize.save()
        purchase.status = Purchase.DECLINED
        purchase.save()
        tr = Transaction()
        tr.receiver = purchase.user
        tr.amount = purchase.prize.cost
        tr.save()
Example #13
0
    def close_positions(goal):
        """
        Create close position requests for all the positions owned by the given goal.
        :param goal: The goal you want to close the positions of.
        :return: A MarketOrderRequest if the goal had positions.
        """

        # Make sure this goal has no open MarketOrderRequests that include this goal.
        async_id = OrderManager.cancel_open_orders(goal)

        # Send whatever neutralising orders need to be sent
        positions = goal.get_positions_all()
        if async_id is None and positions:
            order_request = MarketOrderRequest.objects.create(
                account=goal.account)
            execution_requests = []
            transactions = []
            for position in positions:
                # We should never be short.
                if position.quantity < 0:
                    raise ValueError(
                        "We have a negative position, and we should NEVER have that."
                    )
                transactions.append(
                    Transaction(reason=Transaction.REASON_ORDER,
                                to_goal=goal,
                                amount=position.price * position.quantity))
                execution_requests.append(
                    ExecutionRequest(reason=ExecutionRequest.Reason.WITHDRAWAL,
                                     goal=goal,
                                     asset=Ticker.objects.get(
                                         position.ticker_id),
                                     volume=-position.quantity,
                                     order=order_request,
                                     transaction=transactions[-1]))
            Transaction.objects.bulk_create(transactions)
            ExecutionRequest.objects.bulk_create(execution_requests)
            return order_request
        else:
            # First stage was asynchronous, we need to wait
            # TODO: Queue up another call to close_positions based on the completion of async_id
            raise NotImplementedError("Need to implement async logic.")
Example #14
0
def close_casino(finalize=True):
    for group in Group.objects.all():
        if group.casino_contest:
            if finalize:
                finalize_casino(group)
            with open(os.path.join(MEDIA_ROOT, 'casino_%d.html' % group.id),
                      "w") as f:
                f.write(render_casino(group))
    for session in CasinoSession.objects.all():
        if session.won:
            tr = Transaction()
            tr.receiver = session.user
            tr.amount = session.won
            tr.save()
            session.user.bonuses += session.won
            session.user.save()
    for group in Group.objects.all():
        if group.casino_contest:
            reset_contest(casino_contest)
    CasinoSession.objects.all().delete()
Example #15
0
def casino(req, group_id):
    session = False
    try:
        group = Group.objects.get(id=group_id)
        if CasinoSession.objects.filter(user=req.user, group=group).exists():
            session = True
        if not group.casino_contest:
            raise ValueError
        if not req.user.is_authenticated:
            raise ValueError
        if not User.objects.filter(id=req.user.id,
                                   groups__id=group.id).exists():
            raise ValueError
    except:
        raise Http404()
    if req.POST.get('action') == 'start' and not session:
        try:
            bet = int(req.POST.get('bet'))
            if bet < 0:
                raise ValueError
            if bet > req.user.bonuses:
                raise ValueError
            sess = CasinoSession()
            sess.group = group
            sess.user = req.user
            sess.bet = bet
            sess.save()
            sess.start_contest()
            transaction = Transaction()
            transaction.sender = req.user
            transaction.amount = bet
            transaction.save()
            req.user.bonuses -= bet
            req.user.save()
            return redirect('/casino/%d/play' % group.id)
        except:
            raise Http404()

    return render(req,
                  'casino.html',
                  context=dict(group=group, session=session))
Example #16
0
            else:
                product = Product(name=sheet.cell_value(
                    rowIdx, SALES_COLUMN_IDX_FOR_PRODUCT_NAME), )
                ProductDic[name] = product
                products.append(product)

            # #print(sheet.cell_value(rowIdx, SALES_COLUMN_IDX_FOR_PRODUCT_TOTAL_PRICE))

            transaction = Transaction(
                t_type='PURCHASE',
                product=product,
                client=client,
                date=date,
                volume=float(
                    check(
                        sheet.cell_value(
                            rowIdx, SALES_COLUMN_IDX_FOR_PRODUCT_AMOUNT))),
                amount=float(
                    check(
                        sheet.cell_value(
                            rowIdx,
                            SALES_COLUMN_IDX_FOR_PRODUCT_TOTAL_PRICE))),
            )
            transactions.append(transaction)

        rowIdx += 1

print("Ended Sales ")

# read discount data
discount_files = [
Example #17
0
    def post(self, request):
        try:
            date_t = request.POST["date_t"] if "date_t" in request.POST else None
            date_bank = request.POST["date_bank"] if "date_bank" in request.POST else None
            if date_bank == "":
                date_bank = None
            amount = float(request.POST["amount"].replace(",", "."))
            subject = request.POST["subject"]
            try:
                category = Category.objects.get(pk=request.POST["category"])
            except Category.DoesNotExist:
                return JsonResponse({"success": False,
                                     "message": "Category %s does not exists" % request.POST["category"]})
            try:
                month = Month.objects.get(pk=request.POST["month"]) \
                    if ("month" in request.POST and request.POST["month"] != "") else None
            except Month.DoesNotExist:
                return JsonResponse({"success": False, "message": "Month %s does not exists" % request.POST["month"]})
            tr_id = request.POST["tr_id"] if "tr_id" in request.POST else None
            group_id = request.POST["group_id"] if "group_id" in request.POST else None
            if tr_id == "":
                tr_id = None
        except (KeyError, ValueError):
            traceback.print_exc()
            return JsonResponse({"success": False, "message":
                                 "Bad query. Please contact the support to report the bug"})

        if (group_id is None or group_id == "") and (date_t is None or month is None):
            return JsonResponse({"success": False,
                                 "message": "Bad request (2). please contact the support to report the bug"})

        if group_id is None or group_id == "":
            try:
                date_regex = r"^\d\d/\d\d/\d\d\d\d$"
                if date_t is not None:
                    if not re.match(date_regex, date_t):
                        raise ValueError("Invalid date: %s" % date_t)
                    date_t = functions.format_date(date_t)
                else:
                    raise ValueError("Date is required")
                if date_bank is not None and date_bank != "":
                    if not re.match(date_regex, date_bank):
                        raise ValueError("Invalid date: %s" % date_bank)
                    date_bank = functions.format_date(date_bank)
            except ValueError as e:
                return JsonResponse({"success": False, "message": str(e)})

        try:
            if tr_id is None:
                # Add a new transaction
                try:
                    with db_transaction.atomic():
                        if group_id is None or group_id == "":
                            transaction_group = TransactionGroup(date_t=date_t, date_bank=date_bank, month=month)
                            transaction_group.save()
                        else:
                            try:
                                transaction_group = TransactionGroup.objects.get(pk=int(group_id))
                            except TransactionGroup.DoesNotExist:
                                return JsonResponse({"success": False, "message": "Transaction group does not exists"})
                        transaction = Transaction(amount=amount, subject=subject, category=category,
                                                  group=transaction_group)
                        transaction.save()
                        tr_id = transaction.pk
                except:
                    db_transaction.rollback()
                    traceback.print_exc()
                    return JsonResponse({"success": False,
                                         "message": "An unexpected error occurred. Please contact the support"})
            else:
                # Edit existing transaction
                try:
                    with db_transaction.atomic():
                        try:
                            transaction = Transaction.objects.get(pk=tr_id)
                            transaction_group = transaction.group
                            transaction_group.date_t = date_t
                            transaction_group.date_bank = date_bank
                            transaction_group.month = month
                            transaction_group.save()
                            transaction.amount = amount
                            transaction.subject = subject
                            transaction.category = category
                            transaction.save()
                        except:
                            db_transaction.rollback()
                            raise Exception()
                except Transaction.DoesNotExist:
                    db_transaction.rollback()
                    return JsonResponse({"success": False, "message": "Transaction %s does not exists" % tr_id})
                except:
                    db_transaction.rollback()
                    traceback.print_exc()
                    return JsonResponse({"success": False,
                                         "message": "An unexpected error occurred. Please contact the support"})
        except:
            traceback.print_exc()
            return JsonResponse({"success": False,
                                 "message": "An unexpected error occurred. Please contact the support"})

        return JsonResponse({"success": True,
                             "html": render_to_string("main_content.html",
                                                      {"data": content_data(request.user)}),
                             "tr_id": tr_id})
Example #18
0
    def post(self, request, *args, **kwargs):
        model = ujson.loads(request.POST.get("model", '{}'))
        new_transaction = Transaction()
        if model['account']:
            new_transaction.account = get_object_or_404(
                Goal,
                pk=model['account'],
                account__primary_owner=self.client)

        new_transaction.from_account = None
        new_transaction.to_account = None
        new_transaction.type = model["type"]
        new_transaction.amount = model["amount"]

        if model["fromAccount"]:
            new_transaction.from_account = get_object_or_404(
                Goal,
                pk=model['fromAccount'],
                account__primary_owner=self.client)

        if model["toAccount"]:
            new_transaction.to_account = get_object_or_404(
                Goal,
                pk=model['toAccount'],
                account__primary_owner=self.client)

        new_transaction.save()

        if new_transaction.type == "ACCOUNT_TRANSFER_FROM":
            # transfer shares to the other account
            total_balance = new_transaction.from_account.total_balance
            transaction_amount = float(new_transaction.amount)
            for p in Position.objects.filter(goal=new_transaction.from_account).all():
                transfer_share_size = (p.value/total_balance) * transaction_amount / p.ticker.unit_price
                p.share -= transfer_share_size
                p.save()
                new_position, is_new = Position.objects.get_or_create(goal=new_transaction.to_account, ticker=p.ticker)
                new_position.share += transfer_share_size
                new_position.save()
            new_transaction.status = Transaction.STATUS_EXECUTED
            new_transaction.executed = now()
            new_transaction.save()

        if not new_transaction.account:
            return HttpResponse("null", content_type='application/json')

        nt_return = {
            "id": new_transaction.pk,
            "type": new_transaction.type,
            "amount": new_transaction.amount
        }
        if new_transaction.account:
            nt_return["account"] = new_transaction.account.pk

        if new_transaction.from_account:
            nt_return["fromAccount"] = new_transaction.from_account.pk

        if new_transaction.to_account:
            nt_return["toAccount"] = new_transaction.to_account.pk

        return HttpResponse(ujson.dumps(nt_return),
                            content_type='application/json')
Example #19
0
    def delete(self, request, *args, **kwargs):
        model = ujson.loads(request.POST.get("model", '{}'))
        goal = get_object_or_404(Goal,
                                 pk=model["id"],
                                 account__primary_owner=self.client)
        goal.archived = True
        # remove from financial plan
        # remove automatic deposit and wdw
        #AutomaticWithdrawal.objects.filter(account=goal).delete()
        #AutomaticDeposit.objects.filter(account=goal).delete()

        # move shares
        if goal.total_balance > 0:
            if "transferAllTo" in model and model["transferAllTo"] != "bank":
                to_account = int(model["transferAllTo"])
                transfer_transaction = Transaction()
                transfer_transaction.type = "ACCOUNT_TRANSFER_FROM"
                transfer_transaction.from_account = goal
                transfer_transaction.to_account = get_object_or_404(Goal, pk=to_account,
                                                                    account__primary_owner=self.client)
                transfer_transaction.amount = goal.total_balance
                # transfer shares to the other account
                for p in Position.objects.filter(goal=transfer_transaction.from_account).all():
                    new_position, is_new = Position.objects.get_or_create(goal=transfer_transaction.to_account,
                                                                          ticker=p.ticker)
                    new_position.share += p.share
                    new_position.save()
                    p.delete()

                transfer_transaction.status = Transaction.STATUS_EXECUTED
                transfer_transaction.executed = now()
                transfer_transaction.save()

            else:
                # wdw all the money
                wdw_transaction = Transaction()
                wdw_transaction.account = goal
                wdw_transaction.type = Transaction.REASON_WITHDRAWAL
                wdw_transaction.amount = goal.total_balance
                wdw_transaction.save()
        goal.save()
        return HttpResponse('null', content_type="application/json")
Example #20
0
async def withdraw(ctx, amount=None):
    if await channelcheck(server_list, ctx):
        return

    async with ctx.channel.typing():
        if amount == None:
            embed = discord.Embed(
                title="Missing Arguments",
                description=
                f"To withdraw, you need to do `{bot_prefix}withdraw [amount of coins excluding fee]`. ",
                color=bot_color)
            await ctx.send(embed=embed)
            return

        invalid = False
        records = await sync_to_async(User.objects.filter
                                      )(DiscordID=ctx.author.id)
        bank_config = requests.get(
            'http://45.33.60.42/config?format=json').json()
        try:
            amount = int(amount)
        except:
            if amount == 'all':
                amount = records[0].Coins - (
                    int(bank_config['default_transaction_fee']) +
                    int(bank_config['primary_validator']
                        ['default_transaction_fee']))
            else:
                invalid = True

        if amount < 1:
            invalid = True

        if invalid:
            embed = discord.Embed(
                title="Invalid Argument(s)",
                description="One or more of your passed arguments are invalid",
                color=bot_color)
            await ctx.send(embed=embed)
            return

        if any(records):
            if records[0].Coins < amount + int(
                    bank_config['default_transaction_fee']) + int(bank_config[
                        'primary_validator']['default_transaction_fee']):
                embed = discord.Embed(
                    title="Inadequate Funds",
                    description=
                    f"You do not have enough coins in your discord wallet. \n Use `{bot_prefix}deposit` to add more coins. \n _Transaction fees may apply_",
                    color=bot_color)
                embed.set_author(name=ctx.author.name,
                                 icon_url=ctx.author.avatar_url)
                await ctx.send(embed=embed)
            else:
                bank_config = requests.get(
                    'http://45.33.60.42/config?format=json').json()
                balance_lock = requests.get(
                    f"{bank_config['primary_validator']['protocol']}://{bank_config['primary_validator']['ip_address']}:{bank_config['primary_validator']['port'] or 0}/accounts/{bot_wallet}/balance_lock?format=json"
                ).json()['balance_lock']
                txs = [{
                    'amount': int(amount),
                    'memo': f'Withdrawal for {ctx.author.name}',
                    'recipient': records[0].Address
                }, {
                    'amount': int(bank_config['default_transaction_fee']),
                    'fee': 'BANK',
                    'recipient': bank_config['account_number'],
                }, {
                    'amount':
                    int(bank_config['primary_validator']
                        ['default_transaction_fee']),
                    'fee':
                    'PRIMARY_VALIDATOR',
                    'recipient':
                    bank_config['primary_validator']['account_number'],
                }]

                data = await generate_block(balance_lock, txs, signing_key)
                headers = {
                    'Connection': 'keep-alive',
                    'Accept': 'application/json, text/plain, */*',
                    'User-Agent':
                    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) TNBAccountManager/1.0.0-alpha.43 Chrome/83.0.4103.122 Electron/9.4.0 Safari/537.36',
                    'Content-Type': 'application/json',
                    'Accept-Language': 'en-US'
                }
                r = requests.request("POST",
                                     'http://45.33.60.42/blocks',
                                     headers=headers,
                                     data=data)
                if r:
                    if int(
                            requests.get(
                                f"http://45.33.60.42/accounts/{bot_wallet}/balance?format=json"
                            ).json()['balance']) < amount + int(
                                bank_config['primary_validator']
                                ['default_transaction_fee']) + int(
                                    bank_config['default_transaction_fee']):
                        embed = discord.Embed(
                            title="Error!",
                            description=f"Please try again later.",
                            color=bot_color)
                        embed.set_author(name=ctx.author.name,
                                         icon_url=ctx.author.avatar_url)
                        await ctx.send(embed=embed)
                        return
                    try:
                        user = await sync_to_async(User.objects.filter
                                                   )(Address=records[0].Address
                                                     )
                        await sync_to_async(
                            user.update
                        )(Coins=user[0].Coins -
                          (amount + int(bank_config['primary_validator']
                                        ['default_transaction_fee']) +
                           int(bank_config['default_transaction_fee'])))
                    except Exception as e:
                        print(e)
                    res = requests.get(
                        f'http://45.33.60.42/bank_transactions?limit=1&recipient={records[0].Address}&amount={amount}'
                    ).json()['results'][0]
                    if r.json()['id'] == res['block']['id']:
                        newTX = Transaction(Type="WITHDRAW",
                                            TxID=res["id"],
                                            Amount=int(res['amount']))
                        newTX.save()

                    embed = discord.Embed(
                        title="Coins Withdrawn!",
                        description=
                        f"{amount} coins have been withdrawn to {records[0].Address} succesfully. \n Use `{bot_prefix}status` to check your new balance.",
                        color=bot_color)
                    embed.set_author(name=ctx.author.name,
                                     icon_url=ctx.author.avatar_url)
                    await ctx.send(embed=embed)
                else:
                    print(r.json())
                    embed = discord.Embed(
                        title="Error!",
                        description=f"Please try again later.",
                        color=bot_color)
                    embed.set_author(name=ctx.author.name,
                                     icon_url=ctx.author.avatar_url)
                    await ctx.send(embed=embed)
        else:
            embed = discord.Embed(
                title="Unregistered",
                description=f"No address could be found for {ctx.author.name}",
                color=bot_color)
            embed.set_author(name=ctx.author.name,
                             icon_url=ctx.author.avatar_url)
            await ctx.send(embed=embed)
Example #21
0
def save_record(token, transaction_address, transactionid, amount, source, blockheightid=None, index=0, new_subscription=False, spent_txids=[]):
    """
        token                : can be tokenid (slp token) or token name (bch)
        transaction_address  : the destination address where token had been deposited.
        transactionid        : transaction id generated over blockchain.
        amount               : the amount being transacted.
        source               : the layer that summoned this function (e.g SLPDB, Bitsocket, BitDB, SLPFountainhead etc.)
        blockheight          : an optional argument indicating the block height number of a transaction.
        index          : used to make sure that each record is unique based on slp/bch address in a given transaction_id
    """
    subscription = Subscription.objects.filter(
        address__address=transaction_address             
    )
    
    spent_txids_check = Transaction.objects.filter(txid__in=spent_txids)

    # We are only tracking outputs of either subscribed addresses or those of transactions
    # that spend previous transactions with outputs involving tracked addresses
    if not subscription.exists() and not spent_txids_check.exists():
        return None, None

    address_obj, _ = Address.objects.get_or_create(address=transaction_address)

    try:
        index = int(index)
    except TypeError as exc:
        index = 0

    with trans.atomic():
        
        transaction_created = False

        if token.lower() == 'bch':
            token_obj, _ = Token.objects.get_or_create(name=token)
        else:
            token_obj, created = Token.objects.get_or_create(tokenid=token)
            if created:
                get_token_meta_data.delay(token)

        try:

            #  USE FILTER AND BULK CREATE AS A REPLACEMENT FOR GET_OR_CREATE        
            tr = Transaction.objects.filter(
                txid=transactionid,
                address=address_obj,
                index=index,
            )
            
            if not tr.exists():

                transaction_data = {
                    'txid': transactionid,
                    'address': address_obj,
                    'token': token_obj,
                    'amount': amount,
                    'index': index,
                    'source': source
                }
                transaction_list = [Transaction(**transaction_data)]
                Transaction.objects.bulk_create(transaction_list)
                transaction_created = True
        except IntegrityError:
            return None, None

        transaction_obj = Transaction.objects.get(
            txid=transactionid,
            address=address_obj,
            token=token_obj,
            amount=amount,
            index=index
        )

        if blockheightid is not None:
            transaction_obj.blockheight_id = blockheightid
            if new_subscription:
                transaction_obj.acknowledged = True

            # Automatically update all transactions with block height.
            Transaction.objects.filter(txid=transactionid).update(blockheight_id=blockheightid)

        # Check if address belongs to a wallet
        if address_obj.wallet:
            transaction_obj.wallet = address_obj.wallet

        # Save updates and trigger post-save signals
        transaction_obj.save()
        
        return transaction_obj.id, transaction_created
Example #22
0
async def constant():
    global server_list
    while True:
        try:
            await asyncio.sleep(3)
            r = requests.get(
                f"http://45.33.60.42/bank_transactions?format=json&limit=20&recipient={bot_wallet}"
            )
            info = r.json()
            deposits = await sync_to_async(Transaction.objects.filter
                                           )(Type="DEPOSIT")
            for tx in info["results"]:
                if tx["id"] not in [tx.TxID for tx in deposits]:
                    try:
                        user = await sync_to_async(
                            User.objects.filter)(Address=tx['block']['sender'])
                        await sync_to_async(user.update)(Coins=user[0].Coins +
                                                         int(tx['amount']))
                    except Exception as e:
                        print(e)
                    newTX = Transaction(Type="DEPOSIT",
                                        TxID=tx["id"],
                                        Amount=int(tx['amount']))
                    newTX.save()

                    try:
                        user = await client.fetch_user(user[0].DiscordID)
                        embed = discord.Embed(
                            title="Success",
                            description=
                            f"Succesfully deposited {tx['amount']} coin(s) into your account",
                            color=bot_color)
                        await user.send(embed=embed)
                    except Exception as e:
                        print(e)
            tasks = await sync_to_async(Task.objects.all)()

            for task in tasks:
                if task.Date <= utc.localize(datetime.datetime.utcnow()):
                    if task.Type == "GIVEAWAY":
                        PassIn = json.loads(task.Info)
                        await Giveaway(PassIn["host"], PassIn["message"],
                                       PassIn["guild"], PassIn["channel"],
                                       PassIn["amount"], server_list, client,
                                       bot_color)
                        task.delete()

            server_list = []
            servers = await sync_to_async(Server.objects.all)()
            for server in servers:
                ServerObject = Guild(server.ServerID, server.ChannelID)
                if server.MainChannel != 0:
                    ServerObject.main_channel = server.MainChannel

                if server.AnnouncementChannel != 0:
                    ServerObject.announcement_channel = server.AnnouncementChannel

                server_list.append(ServerObject)

        except:
            pass
Example #23
0
    def post(self, request):
        data = request.POST

        # Check data:
        if "transaction_date" not in data:
            return HttpResponseBadRequest(
                json.dumps({
                    "success": False,
                    "message": _("Invalid request")
                }))
        transaction_date = data.get("transaction_date")
        if not self.is_date_valid(transaction_date):
            return HttpResponseBadRequest(
                json.dumps({
                    "success": False,
                    "message": _("Invalid date")
                }))
        if "transactions" not in data:
            return HttpResponseBadRequest(
                json.dumps({
                    "success": False,
                    "message": _("Invalid request")
                }))
        try:
            transactions = json.loads(data.get("transactions"))
        except ValueError:
            return HttpResponseBadRequest(
                json.dumps({
                    "success": False,
                    "message": _("Invalid request")
                }))

        for i in range(0, len(transactions)):
            valid, tr_or_message = self.is_transaction_valid(transactions[i])
            if valid:
                transactions[i] = tr_or_message
            else:
                return HttpResponseBadRequest(json.dumps({"success": False, "message": _("At least one transaction "
                                                                                         "is not valid") + \
                                                          ("" if tr_or_message is None else tr_or_message)}))

        if "month" not in data or (type(data.get("month")) != int and
                                   ((type(data.get("month")) == str
                                     and not data.get("month").isdigit())
                                    or type(data.get("month")) != str)):
            return HttpResponseBadRequest(
                json.dumps({
                    "success": False,
                    "message": _("Invalid request")
                }))
        try:
            month = Month.objects.get(pk=int(data.get("month")))
        except Month.DoesNotExist:
            return HttpResponseBadRequest(
                json.dumps({
                    "success": False,
                    "message": _("Invalid month")
                }))

        # Insert data:
        try:
            with db_transaction.atomic():
                tr_group = TransactionGroup(
                    date_t=functions.format_date(transaction_date),
                    month=month)
                tr_group.save()

                for transaction in transactions:
                    tr = Transaction(group=tr_group,
                                     subject=transaction["description"],
                                     amount=transaction["amount"],
                                     category=transaction["category"])
                    tr.save()
        except:
            db_transaction.rollback()
            return HttpResponseServerError(
                json.dumps({
                    "success": False,
                    "message": _("Unexpected server error")
                }))

        response_data = {'success': True}
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json")
Example #24
0

###################################################

with open('tree_search_time.json') as f:
	search_data = json.load(f)

COLUMNS = ['time', 'name', 'price_3', 'price', 'price_increase', 'search_time']

search_df = pd.DataFrame(search_data, columns = COLUMNS)

search_dict = search_df.T.to_dict('list')


for k,v in search_dict.items():
	transaction = Transaction()
	transaction.selling_time = v[0]
	transaction.name = v[1]
	transaction.buying_price = v[2]
	transaction.actual_price = v[3]
	transaction.price_increase = v[4]
	transaction.search_time = v[5]

	transaction.save()



def find_result(col):
	num_trade = len(testing[testing[col] == 1])
	percent = testing[testing[col] == 1]['did_price_033'].mean()
	exp = testing[testing[col] == 1]['price_increase'].mean()
Example #25
0
    def handle_file(self, file, user):
        with open(f'main\\static\\data\\csv{user.id}.csv',
                  'wb+') as destination:
            for chunk in file.chunks():
                destination.write(chunk)

        cost, income, account = None, None, None
        with open(f'main\\static\\data\\csv{user.id}.csv',
                  'r',
                  encoding='windows-1251') as file:
            reader = csv.reader(file)
            row_num = 0
            for row in reader:
                if row_num == 0:
                    account_name = row[0].split(':')[1].split('-')[0]
                    account_name = account_name.strip()
                    amount = int(float(row[-7].split(':')[-1].split(' ')[0]))
                    acc_cur = row[-7].split(':')[-1].split(' ')[1]
                    account = Account.objects.filter(
                        Q(user=user) & Q(name__startswith=account_name)
                        & Q(delete=False)).first()
                    if not account:
                        account = Account(
                            name=account_name,
                            user=user,
                            amount=amount,
                            currency=acc_cur,
                        )
                        account.save()

                    income = Income.objects.filter(
                        Q(user=user) & Q(name__startswith=account_name)
                        & Q(delete=False)).first()
                    if not income:
                        income = Income(name=f'{account_name}_income',
                                        user=user,
                                        currency=acc_cur)
                        income.save()

                    cost = Cost.objects.filter(
                        Q(user=user) & Q(name__startswith=account_name)
                        & Q(delete=False)).first()
                    if not cost:
                        cost = Cost(name=f'{account_name}_cost',
                                    user=user,
                                    currency=acc_cur)
                        cost.save()
                elif row_num > 2:
                    j = 0
                    for j in range(len(row) - 1, 0, -1):
                        if row[j] == '':
                            continue
                        break
                    date = row[0].split('.')
                    date.reverse()
                    date = '-'.join(date)
                    amount = int(float(row[j - 3]))
                    cur = row[j - 2]
                    comment = row[1].split()
                    comment = ' '.join(comment)
                    if amount > 0:
                        Transaction(data_from=date,
                                    user=user,
                                    transaction_from=income,
                                    transaction_to=account,
                                    choice_currency=cur,
                                    amount=amount,
                                    comment=comment[:100]).save()
                    else:
                        Transaction(data_from=date,
                                    user=user,
                                    transaction_from=account,
                                    transaction_to=cost,
                                    choice_currency=cur,
                                    amount=-1 * amount,
                                    comment=comment[:100]).save()
                row_num += 1
        os.remove(f'main\\static\\data\\csv{user.id}.csv')
Example #26
0
class GoalRebalance(TemplateView, AdminView):
    template_name = 'admin/betasmartz/transaction-form-2.html'
    goal = None
    transaction = None

    def get_context_data(self, **kwargs):
        portfolio_set = Platform.objects.first().portfolio_set
        ctx = super(GoalRebalance, self).get_context_data(**kwargs)
        ctx["transaction"] = serializers.serialize('json', [self.transaction])
        ctx["amount"] = self.transaction.amount
        ctx["account"] = json.loads(
            serializers.serialize('json',
                                  [self.transaction.account]))[0]["fields"]
        ctx["account"][
            "owner_full_name"] = self.transaction.account.account.primary_owner.user.get_full_name(
            )
        ctx["account"][
            "advisor_full_name"] = self.transaction.account.account.primary_owner.advisor.user.get_full_name(
            )
        ctx["account"][
            "firm_name"] = self.transaction.account.account.primary_owner.advisor.firm.name
        ctx["account"]["fee"] = self.transaction.account.account.fee

        ctx["tickers"] = Ticker.objects.filter(
            asset_class__in=portfolio_set.asset_classes.all())

        goal = self.transaction.account
        target_allocation_dict = goal.target_allocation

        tickers_pk = []
        tickers_prices = []
        target_allocation = []
        current_shares = []
        result_dict = {}
        current_shares_dict = {}
        price_dict = {}
        result_a = []
        target_allocation_dict_2 = {}

        for ticker in ctx["tickers"]:
            tickers_pk.append(ticker.pk)
            tickers_prices.append(ticker.unit_price)
            target_allocation.append(
                target_allocation_dict.get(ticker.asset_class.name, 0))
            positions = Position.objects.filter(goal=self.transaction.account,
                                                ticker=ticker).all()
            cs = 0
            if positions:
                for p in positions:
                    cs += p.share
            current_shares.append(cs)
        if self.transaction.status == Transaction.STATUS_PENDING:

            if self.transaction.type == TRANSACTION_TYPE_ALLOCATION:
                result_a = solve_shares_re_balance(current_shares,
                                                   tickers_prices,
                                                   target_allocation)
                ctx["amount"] = 1
                ctx["account"]["fee"] = sum(abs(
                    result_a * tickers_prices)) * ctx["account"]["fee"]

        for i in range(len(result_a)):
            result_dict[str(tickers_pk[i])] = result_a[i]
            current_shares_dict[str(tickers_pk[i])] = current_shares[i]
            price_dict[str(tickers_pk[i])] = tickers_prices[i]
            target_allocation_dict_2[str(tickers_pk[i])] = target_allocation[i]

        ctx["price_dict"] = price_dict
        ctx["target_allocation_dict"] = target_allocation_dict_2
        ctx["current_shares_dict"] = current_shares_dict
        ctx["result_dict"] = result_dict
        ctx["account"] = json.dumps(ctx["account"])
        ctx["tickers"] = serializers.serialize('json', ctx["tickers"])
        ctx["is_executed"] = self.transaction.status == Transaction.STATUS_EXECUTED
        return ctx

    def dispatch(self, request, *args, **kwargs):
        self.goal = get_object_or_404(Goal, pk=kwargs["pk"])
        self.transaction = Transaction(account=self.goal,
                                       amount=self.goal.allocation,
                                       type=TRANSACTION_TYPE_ALLOCATION,
                                       status=Transaction.STATUS_PENDING,
                                       created=now().today())
        response = super(GoalRebalance, self).dispatch(request, *args,
                                                       **kwargs)
        return response

    def post(self, request, *args, **kwargs):
        data = json.loads(request.POST.get("data"))
        positions = []
        new_amount = 0
        old_amount = 0
        new_shares = []
        old_shares = []

        for pk, v in data.items():
            if v != 0:
                ticker = Ticker.objects.get(pk=pk)
                new_p = Position(ticker=ticker,
                                 goal=self.transaction.account,
                                 share=v)
                positions.append(new_p)
                new_amount += new_p.value
                new_shares.append(new_p.value)

        for old_p in self.transaction.account.positions.all():
            old_amount += old_p.value
            old_shares.append(old_p.value)

        amount = abs(new_amount - old_amount)
        # delete old positions
        self.transaction.account.positions.all().delete()
        # save new
        # mark transaction as executed
        self.transaction.executed = now()

        self.transaction.type = Transaction.REASON_REBALANCE
        self.transaction.status = Transaction.STATUS_EXECUTED

        list(map(lambda x: x.save(), positions))
        self.transaction.save()
        self.goal.drift = self.goal.get_drift
        self.goal.save()

        return HttpResponseRedirect('/admin/main/goal')
Example #27
0
 def post(self, request, *args, **kwargs):
     tr = Transaction(amount=request.POST.get("amount"),
                      type=request.POST.get("type"))
     tr.save()
     return redirect("/")
Example #28
0
def create_transaction(user_from=None, user_to=None, description='transaction_description_test', status=True, amount=10):
    user_from = user_from or create_user_profile()
    user_to = user_to or create_user_profile()
    transaction = Transaction(**locals())
    transaction.save()
    return transaction