def join(request):
    transaction_id = request.POST['trans']
    selected_level = request.POST['selected_level']
    ac = Authentication(request)
    user_id = ac.get_user_session()
    error_messages = []
    error_messages.extend(validate_level_selection(selected_level))
    error_messages.extend(
        validate_level_already_taken(transaction_id, selected_level))
    error_messages.extend(validate_user_count_exceeded(transaction_id))
    error_messages.extend(
        validate_level_users(transaction_id, user_id, selected_level))
    parent_trade = get_parent_trade(transaction_id)
    error_messages.extend(
        validate_changes_allowed_time_exceeded(
            parent_trade["changes_allowed_time"]))

    if error_messages:
        return JsonResponse(Helper.get_json_response(False, {},
                                                     error_messages))
    current_user = Helper.get_user_by_id(user_id)
    persist_join(user_id, transaction_id, parent_trade, selected_level,
                 current_user)
    return JsonResponse(
        Helper.get_json_response(True, {}, ["Trade joined successfully"]))
Ejemplo n.º 2
0
def get_pending_order(request):
    post = request.POST
    transaction_id = post['transaction_id']
    user_id = post['user_id']
    result = Trading.get_transaction_by_id(transaction_id, user_id)
    if not result:
        return JsonResponse(
            Helper.get_json_response(False, {},
                                     ["Trade data is not available"]))
    user_data = Helper.get_user_by_id(user_id)

    data = dict()
    data["transaction_id"] = result["transaction_id"]
    data["created_date"] = result["created_date"]
    data["trade_type"] = result["trade_type"].capitalize()
    data["purchase_type"] = result["purchase_type"].capitalize()
    data["currency"] = result["currency"]
    data["amount"] = result["amount"]
    data["start_time"] = str(result["start_time"])
    data["end_time"] = str(result["end_time"])
    data["changes_allowed_time"] = str(result["changes_allowed_time"])
    data["outcome"] = result["outcome"].capitalize()
    data["status"] = result["status"].capitalize()
    data["amount_currency"] = user_data["currency"]

    return JsonResponse(Helper.get_json_response(True, data, []))
def validate_withdrawal_amount(user_id, amount):
    if not amount:
        return ["Please enter amount to withdraw"]
    if not amount.isnumeric():
        return ['Please enter a valid amount']
    amount = float(amount)
    if amount < 1:
        return ['Amount should be greater than 0']

    current_user = Helper.get_user_by_id(user_id)
    if current_user["vcurrency"] <= float(amount):
        return ['Withdrawal amount cannot be greater than the account balance']
    return []
def view(request):
    ac = Authentication(request)
    # if user is not logged in redirect to login page
    data = dict()
    if not ac.is_user_logged_in():
        return redirect('/login')

    user_id = ac.get_user_session()
    data['auth'] = ac.is_user_logged_in()
    data["pending_trades"] = Helper.get_latest_pending_trades(user_id)
    data["latest_outcomes"] = Helper.get_latest_outcome_trades(user_id)
    data["user_currency"] = Helper.get_user_by_id(user_id)['currency']
    return render(request, 'dashboard.html', data)
def withdraw(request, user_id):
    amount = request.POST['withdraw_amount']
    error_messages = []
    error_messages.extend(validate_withdrawal_amount(user_id, amount))
    if error_messages:
        return error_messages
    current_user = Helper.get_user_by_id(user_id)
    new_amount = current_user["vcurrency"] - float(amount)
    cursor = connection.cursor()
    q = f"UPDATE user_by_id SET vcurrency = {new_amount} WHERE id = {user_id}"
    cursor.execute(q)

    return []
def deposit(request, user_id):
    amount = request.POST['vcurrency']
    error_messages = []
    error_messages.extend(UserHelper.validate_amount(amount))
    if error_messages:
        return error_messages

    user_data = Helper.get_user_by_id(user_id)
    amount = float(amount)
    balance = user_data['vcurrency'] + amount
    user_settings = UserById(id=user_id, vcurrency=balance)
    user_settings.update()
    pass
def persist_transactions_by_state(transaction_id, user_id, parent_trade):
    current_user = Helper.get_user_by_id(user_id)
    converted_amount = Helper.convert_currency(parent_trade['amount'],
                                               parent_trade['amount_currency'],
                                               current_user['currency'])

    fields = "(transaction_id,user_id,currency,purchase_type,outcome,status, created_date, amount, trade_type)"

    values = f"({transaction_id}, {user_id},'{parent_trade['currency']}','{parent_trade['purchase_type']}'," \
             f"'{parent_trade['outcome']}','{parent_trade['status']}','{created_date}',{converted_amount}," \
             f"'{parent_trade['trade_type']}')"

    transactions_by_state = f"INSERT INTO transactions_by_state {fields} VALUES {values}"
    cursor = connection.cursor()
    cursor.execute(transactions_by_state)
def update_password(request, user_id):
    crrpassword = request.POST['crrpassword']
    password = request.POST['password']
    repassword = request.POST['repassword']
    error_message = []
    user_data = Helper.get_user_by_id(user_id)

    error_message.extend(
        validate_current_password(crrpassword, user_data['email']))
    error_message.extend(validate_new_password(password, repassword))
    if error_message:
        return error_message

    new_pass = Helper.password_encrypt(password)
    q = UserCredential(email=user_data['email'], password=new_pass)
    q.update()
def settings(request):
    ac = Authentication(request)
    # if user is not logged in redirect to login page
    if not ac.is_user_logged_in():
        return redirect('/login')

    ac = Authentication(request)
    user_id = ac.get_user_session()
    data = dict()
    if request.method == "POST":
        action = request.POST['action']
        if action == "Update":
            errors = update_settings(request, user_id)
            if errors:
                data['errors'] = errors
            else:
                data['success'] = "General has been updated successfully"

        if action == "Change password":
            errors = update_password(request, user_id)
            if errors:
                data['errors'] = errors
            else:
                data['success'] = "Password has been updated successfully"

        if action == "Deposit":
            errors = deposit(request, user_id)
            if errors:
                data['errors'] = errors
            else:
                data['success'] = "Money has been deposited successfully"

        if action == "Withdraw":
            errors = withdraw(request, user_id)
            if errors:
                data['errors'] = errors
            else:
                data['success'] = "Money withdraw is successful"

    user_data = Helper.get_user_by_id(user_id)

    data['user_data'] = user_data
    data['countries'] = Helper.get_countries()
    data['auth'] = ac.is_user_logged_in()

    return render(request, 'settings.html', data)
def persist_user_transactions(user_id, transaction_id, parent_trade,
                              selected_level):
    current_user = Helper.get_user_by_id(user_id)

    converted_amount = Helper.convert_currency(parent_trade['amount'],
                                               parent_trade['amount_currency'],
                                               current_user['currency'])

    price_range = get_selected_level_price(parent_trade['levels_price'],
                                           selected_level)

    available_levels = get_available_levels(parent_trade['available_levels'],
                                            selected_level)

    level_owners = add_level_owners(parent_trade['level_owners'], user_id,
                                    selected_level)
    start_time = Helper.get_time_formatted(parent_trade['start_time'])
    end_time = Helper.get_time_formatted(parent_trade['end_time'])
    changes_allowed_time = Helper.get_time_formatted(
        parent_trade['changes_allowed_time'])

    fields = "(transaction_id,user_id,created_date,trade_type,purchase_type,currency,staring_price," \
             "amount,amount_currency,start_time,end_time,changes_allowed_time,outcome,status,level_pips,levels_price,level_owners," \
             "join_date,level_start_price,level_end_price,level_selected,created_by,parent_id,child,available_levels)"

    values = f"({transaction_id},{user_id},'{created_date}','{parent_trade['trade_type']}'," \
             f"'{parent_trade['purchase_type']}','{parent_trade['currency']}',{parent_trade['staring_price']}," \
             f"{converted_amount},'{current_user['currency']}','{start_time}','{end_time}'," \
             f"'{changes_allowed_time}','{parent_trade['outcome']}','{parent_trade['status']}'," \
             f"{parent_trade['level_pips']},'{parent_trade['levels_price']}'," \
             f"'{level_owners}'," \
             f"'{Helper.get_current_time_formatted()}',{price_range['range'][0]},{price_range['range'][1]}," \
             f"{selected_level},{parent_trade['created_by']},{parent_trade['user_id']},{True}, {available_levels})"

    user_transactions = f"INSERT INTO user_transactions {fields} VALUES {values}"
    cursor = connection.cursor()
    cursor.execute(user_transactions)
    Trading.save_levels_general_stats(user_id, selected_level,
                                      converted_amount,
                                      parent_trade['purchase_type'])
Ejemplo n.º 11
0
def get_transaction(request):
    ac = Authentication(request)
    # if user is not logged in response user not exist
    if not ac.is_user_logged_in():
        return JsonResponse(
            Helper.get_json_response(False, [], ['Please login']))
    post = request.POST

    trade = Trading.get_transaction_by_id(post['transaction_ref'],
                                          post['trade_owner'])
    if not trade:
        return JsonResponse(
            Helper.get_json_response(False, [], ["Trade not available"]))
    user_id = ac.get_user_session()

    current_user = Helper.get_user_by_id(user_id)
    trade_data = dict()
    trade_data['contract_type'] = trade['trade_type']
    trade_data['transaction_ref'] = trade['transaction_id']
    trade_data['purchase_type'] = trade['purchase_type']
    trade_data['start_time'] = trade['start_time']
    trade_data['end_time'] = trade['end_time']
    if trade['trade_type'] == Types.LEVELS.value:
        trade_data['amount'] = Helper.convert_currency(
            trade['amount'], trade['amount_currency'],
            current_user['currency'])
        trade_data['selected_level'] = trade['level_selected']
        trade_data['user_count'] = 4 - len(trade['available_levels'])
        trade_data['available_levels'] = trade['available_levels']
    else:
        trade_data['amount'] = trade['amount']
    trade_data['user_currency'] = current_user['currency']
    trade_data['staring_price'] = trade['staring_price']
    trade_data['closing_price'] = trade['closing_price']
    trade_data['outcome'] = trade['outcome']
    trade_data['status'] = trade['status']

    return JsonResponse(Helper.get_json_response(True, [trade_data], []))
def statements(request):
    ac = Authentication(request)
    # if user is not logged in redirect to login page
    if not ac.is_user_logged_in():
        return redirect('/login')
    data = dict()
    user_id = ac.get_user_session()
    user_data = Helper.get_user_by_id(user_id)
    data['user_data'] = user_data
    if request.method == "POST":
        data['results'] = search(request)

    if request.method == "GET":
        data['results'] = get_initial_list(user_id)
    status = []
    outcome = []
    [outcome.append(e.value) for e in Outcome]
    [status.append(e.value) for e in Status]
    data["trading_status"] = status
    data["trading_outcome"] = outcome
    data['today_date'] = datetime.now().strftime("%Y-%m-%d")
    data['auth'] = ac.is_user_logged_in()
    data['current_user'] = user_id
    return render(request, 'statements.html', data)
def level_based_search(request):
    ac = Authentication(request)
    # if user is not logged in redirect to login page
    if not ac.is_user_logged_in():
        return redirect('/login')

    data = dict()
    data['results'] = []
    if request.method == "POST":
        form = request.POST['form']
        if form == "search":
            data['results'] = search(request)

    if request.method == "GET":
        data['results'] = initial_search(request)

    data['purchase_type'] = Helper.get_purchase_type_list()
    data['currency_pairs'] = Helper.get_currency_pairs()
    user_id = ac.get_user_session()
    current_user = Helper.get_user_by_id(user_id)
    data['user_currency'] = current_user["currency"]
    data['auth'] = ac.is_user_logged_in()
    data['current_user'] = user_id
    return render(request, 'level_trade_search.html', data)
def get_initial_chart_data(user_id):
    cursor = connection.cursor()
    start = date.today() - timedelta(days=10)
    response = dict()
    for stst in StatKeys:
        result = cursor.execute(f"SELECT * FROM states WHERE user_id = {user_id} "
                                f"AND type = '{stst.value}'and date >= '{start}'")
        if result:
            df = pd.DataFrame(result)

            item = dict()

            item['date'] = df['date'].astype(str).to_json(orient='records')
            item['value'] = df['value'].astype(float).to_json(orient='records')
            response[stst.value] = item
        else:
            item = dict()

            item['date'] = json.dumps([])
            item['value'] = json.dumps([])
            response[stst.value] = item

    response[StatKeys.LEVEL_1.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_1.value)
    response[StatKeys.LEVEL_2.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_2.value)
    response[StatKeys.LEVEL_3.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_3.value)
    response[StatKeys.LEVEL_4.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_4.value)

    response[StatKeys.LEVEL_1_INVST.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_1_INVST.value)
    response[StatKeys.LEVEL_2_INVST.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_2_INVST.value)
    response[StatKeys.LEVEL_3_INVST.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_3_INVST.value)
    response[StatKeys.LEVEL_4_INVST.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_4_INVST.value)

    response[StatKeys.LEVEL_1_WON_COUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_1_WON_COUNT.value)
    response[StatKeys.LEVEL_2_WON_COUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_2_WON_COUNT.value)
    response[StatKeys.LEVEL_3_WON_COUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_3_WON_COUNT.value)
    response[StatKeys.LEVEL_4_WON_COUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_4_WON_COUNT.value)

    response[StatKeys.LEVEL_1_LOSS_COUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_1_LOSS_COUNT.value)
    response[StatKeys.LEVEL_2_LOSS_COUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_2_LOSS_COUNT.value)
    response[StatKeys.LEVEL_3_LOSS_COUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_3_LOSS_COUNT.value)
    response[StatKeys.LEVEL_4_LOSS_COUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_4_LOSS_COUNT.value)

    response[StatKeys.LEVEL_1_WON_AMOUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_1_WON_AMOUNT.value)
    response[StatKeys.LEVEL_2_WON_AMOUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_2_WON_AMOUNT.value)
    response[StatKeys.LEVEL_3_WON_AMOUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_3_WON_AMOUNT.value)
    response[StatKeys.LEVEL_4_WON_AMOUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_4_WON_AMOUNT.value)

    response[StatKeys.LEVEL_1_LOSS_AMOUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_1_LOSS_AMOUNT.value)
    response[StatKeys.LEVEL_2_LOSS_AMOUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_2_LOSS_AMOUNT.value)
    response[StatKeys.LEVEL_3_LOSS_AMOUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_3_LOSS_AMOUNT.value)
    response[StatKeys.LEVEL_4_LOSS_AMOUNT.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVEL_4_LOSS_AMOUNT.value)

    response[StatKeys.BINARY.name] = Helper.get_general_stat_by_key(user_id, StatKeys.BINARY.value)
    response[StatKeys.LEVELS.name] = Helper.get_general_stat_by_key(user_id, StatKeys.LEVELS.value)
    response["all_won_count"] = Helper.get_general_stat_by_user(user_id, StatKeys.WON.value)
    response["all_lass_count"] = Helper.get_general_stat_by_user(user_id, StatKeys.LOSS.value)
    response["all_draw_count"] = Helper.get_general_stat_by_user(user_id, StatKeys.DRAW.value)
    response["all_won_amount"] = Helper.get_general_stat_by_user(user_id, StatKeys.D_WON.value)
    response["all_loss_amount"] = Helper.get_general_stat_by_user(user_id, StatKeys.D_LOSS.value)
    response["user_currency"] = Helper.get_user_by_id(user_id)['currency']
    return response
Ejemplo n.º 15
0
def create_trade(req):
    post = req.POST
    currency = post['currency']
    time_to_close = post['time_to_close']
    time_slot = post['time_slot']
    time_count = post['time_count']
    end_date = post['end_date']
    end_time = post['end_time']
    amount = post['amount']
    gap_pips = post['gap_pips']
    select_level = post['select_level']
    purchase = post['purchase']
    trade_type = 'levels'
    start_time = datetime.now()

    ac = Authentication(req)
    user_id = ac.get_user_session()

    trade_start_time = datetime.now()
    error_messages = []
    error_messages.extend(Trading.validate_currency(currency))
    error_messages.extend(validate_pip_gaps(gap_pips))
    error_messages.extend(validate_levels(select_level))
    error_messages.extend(Trading.validate_time_to_close(time_to_close))
    error_messages.extend(
        Trading.validate_closing_types(time_to_close, time_slot, time_count,
                                       end_date, end_time))
    error_messages.extend(Trading.validate_amount(amount, user_id))
    error_messages.extend(
        validated_end_date(time_to_close, end_date, end_time, time_slot,
                           time_count, start_time))
    # final method to get selected levels
    levels_price = get_price_range_by_level(currency, gap_pips, purchase)

    # final method to get selected level
    selected_level = get_selected_level(select_level, currency, gap_pips,
                                        purchase)

    # final method to get trade closing time
    trade_closing_time = get_trade_end_time(time_to_close, end_date, end_time,
                                            time_slot, time_count, start_time)
    error_messages.extend(Trading.validate_close_time_day(trade_closing_time))
    error_messages.extend(Trading.validate_end_time(trade_closing_time))

    if error_messages:
        return JsonResponse(Helper.get_json_response(False, {},
                                                     error_messages))
    price = Helper.get_current_price(currency)
    changes_allowed_time = Trading.get_trade_changing_blocked_time(
        start_time, trade_closing_time)
    level_owners = get_level_owner(select_level, user_id)

    time_now_formatted = Helper.get_current_time_formatted()

    time_now = datetime.strptime(time_now_formatted, '%Y-%m-%d %H:%M:%S.%f%z')

    purchase_type = Trading.get_trade_type(purchase)
    available_levels = get_available_levels(Levels.levels.value, select_level)

    current_user = Helper.get_user_by_id(user_id)
    user_currency = current_user['currency']
    user_transaction = TransactionsByUser(user_id=user_id,
                                          created_date=time_now)
    user_transaction.save()

    query = f"SELECT * FROM transactions_by_user WHERE user_id = {user_id} and created_date = '{time_now_formatted}'"
    cursor = connection.cursor()
    transaction_id = cursor.execute(query)
    transaction_id = transaction_id[0]["id"]

    user_transactions = f"INSERT INTO user_transactions " \
                        f"(transaction_id,user_id,created_date,trade_type,purchase_type,currency,staring_price,amount," \
                        f"start_time,end_time,changes_allowed_time,outcome,status,level_pips, levels_price,level_owners," \
                        f"join_date,level_start_price,level_end_price,level_selected,created_by,child," \
                        f"available_levels,amount_currency) " \
                        f"VALUES " \
                        f"({transaction_id},{user_id},'{time_now_formatted}','{Types.LEVELS.value}','{purchase_type}'," \
                        f"'{currency}',{float(price)},{float(amount)},'{Helper.get_time_formatted(trade_start_time)}'," \
                        f"'{Helper.get_time_formatted(trade_closing_time)}'," \
                        f"'{Helper.get_time_formatted(changes_allowed_time)}','{Outcome.NONE.value}'," \
                        f"'{Status.STARTED.value}',{int(gap_pips)},'{json.dumps(levels_price)}','{level_owners}'," \
                        f"'{time_now_formatted}',{selected_level['range'][0]},{selected_level['range'][1]}," \
                        f"{selected_level['level']},{user_id},{False},{available_levels},'{current_user['currency']}')"
    cursor.execute(user_transactions)

    transactions_by_state = f"INSERT INTO transactions_by_state " \
                            f"(transaction_id,user_id,currency,purchase_type,outcome,status,created_date,amount," \
                            f"trade_type) " \
                            f"VALUES " \
                            f"({transaction_id},{user_id},'{currency}','{purchase_type}','{Outcome.NONE.value}'," \
                            f"'{Status.STARTED.value}','{time_now_formatted}',{float(amount)},'{Types.LEVELS.value}')"
    cursor.execute(transactions_by_state)

    transactions_levels_status = f"INSERT INTO transactions_levels_status " \
                                 f"(transaction_id,user_id,outcome,purchase_type,currency,status,created_date,amount," \
                                 f"trade_type,start_time,end_time,available_levels,amount_currency) " \
                                 f"VALUES " \
                                 f"({transaction_id},{user_id},'{Outcome.NONE.value}','{purchase_type}','{currency}'," \
                                 f"'{Status.STARTED.value}','{time_now_formatted}',{float(amount)}," \
                                 f"'{Types.LEVELS.value}','{Helper.get_time_formatted(trade_start_time)}'," \
                                 f"'{Helper.get_time_formatted(trade_closing_time)}',{available_levels}, '{user_currency}')"

    cursor.execute(transactions_levels_status)

    transactions_by_end_time = f"INSERT INTO transactions_by_end_time " \
                               f"(transaction_id,user_id,status,trade_type,end_time) " \
                               f"VALUES " \
                               f"({transaction_id},{user_id},'{Status.STARTED.value}','{Types.LEVELS.value}'," \
                               f"'{Helper.get_time_formatted(trade_closing_time)}')"

    cursor.execute(transactions_by_end_time)

    transactions_changes_allowed_time = f"INSERT INTO transactions_changes_allowed_time " \
                                        f"(transaction_id,user_id,status,changes_allowed_time) " \
                                        f"VALUES " \
                                        f"({transaction_id},{user_id},'{Status.STARTED.value}'," \
                                        f"'{Helper.get_time_formatted(changes_allowed_time)}')"

    cursor.execute(transactions_changes_allowed_time)

    level_based_user_counts = f"INSERT INTO level_based_user_counts " \
                              f"(transaction_id,user_count) " \
                              f"VALUES " \
                              f"({transaction_id},1)"

    cursor.execute(level_based_user_counts)

    level_based_user_levels = f"INSERT INTO level_based_user_levels " \
                              f"(transaction_id,level_number) " \
                              f"VALUES " \
                              f"({transaction_id},{selected_level['level']})"

    cursor.execute(level_based_user_levels)

    level_based_by_user_id = f"INSERT INTO level_based_by_user_id " \
                             f"(transaction_id,owner,user_id) " \
                             f"VALUES " \
                             f"({transaction_id},{True},{user_id})"

    cursor.execute(level_based_by_user_id)

    updated_amount = float(current_user['vcurrency']) - float(amount)
    # update account balance
    user_vcurrency = f"UPDATE  user_by_id SET vcurrency = {updated_amount} WHERE id = {user_id}"
    cursor.execute(user_vcurrency)
    Helper.store_state_value(user_id, StatKeys.BALANCE.value, amount,
                             'subtract')
    Helper.store_state_value(user_id, StatKeys.NUM_TRADES.value, 1, 'add')
    Helper.store_state_value(user_id, StatKeys.LEVELS.value, 1, 'add')
    Trading.save_purchase_stats(user_id, purchase_type)
    Trading.save_levels_stats(user_id, select_level)
    Trading.save_levels_general_stats(user_id, select_level, amount,
                                      purchase_type)
    return JsonResponse(
        Helper.get_json_response(True, {
            'transaction_id': str(transaction_id),
            "user_id": str(user_id)
        }, ['Trade created successfully']))