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"]))
def close_order(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'])) user_id = ac.get_user_session() post = request.POST transaction_id = post['transaction_id'] transaction = Trading.get_transaction_by_id(transaction_id, user_id) if not transaction: return JsonResponse( Helper.get_json_response(False, {}, ["Trade data is not available"])) if Trading.validate_changes_allowed_time_exceeded( transaction['changes_allowed_time']): return JsonResponse( Helper.get_json_response( False, {}, ["Trade closing time is expired and cannot be closed"])) update_transactions_by_state_outcome(transaction, Status.FINISHED.value, Outcome.NONE.value) Trading.pay_back(user_id, transaction['amount']) return JsonResponse( Helper.get_json_response(True, {}, ['Trade has been closed successfully']))
def join_trade(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'])) return join(request)
def chart(request): ac = Authentication(request) # if user is not logged in redirect to login page if not ac.is_user_logged_in(): return JsonResponse(Helper.get_json_response(False, [], ["Unauthorized Access"])) post = request.POST start_date = post['start_date'] end_date = post['end_date'] user_id = ac.get_user_session() data = [] if not start_date and not end_date: return JsonResponse(Helper.get_json_response(True, get_initial_chart_data(user_id), [])) stat_key = post['type'] if stat_key == "buy_sell": return JsonResponse( get_chart_by_state_keys(user_id, [StatKeys.BUY.value, StatKeys.SELL.value], start_date, end_date)) if stat_key == "win_loss_count": return JsonResponse( get_chart_by_state_keys(user_id, [StatKeys.WON.value, StatKeys.LOSS.value], start_date, end_date)) if stat_key == "win_loss_amount": return JsonResponse( get_chart_by_state_keys(user_id, [StatKeys.D_WON.value, StatKeys.D_LOSS.value], start_date, end_date)) return JsonResponse(get_filtered_chart_data(user_id, start_date, end_date, stat_key))
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') cursor = connection.cursor() data["currency_pairs"] = cursor.execute("SELECT * FROM currency_pairs") data['auth'] = ac.is_user_logged_in() return render(request, 'insights.html', data)
def chart_view(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() if request.method == "POST": pass data['auth'] = ac.is_user_logged_in() return render(request, 'charts.html', data)
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 levels(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 = Trading.load_static_data() if request.method == "POST": data['errors'] = create_trade(request) data['auth'] = ac.is_user_logged_in() user_id = ac.get_user_session() data['current_user'] = user_id return render(request, 'level_based.html', data)
def initial_search(request): cursor = connection.cursor() results = cursor.execute( f"SELECT * FROM transactions_levels_status WHERE status = '{Status.STARTED.value}'" ) if not results: return [] ac = Authentication(request) user_id = ac.get_user_session() df = pd.DataFrame(results) df = df.loc[df['user_id'] != user_id] df = df.sort_values(by='created_date', ascending=False) return df.head(5).iterrows()
def register(request): ac = Authentication(request) if ac.is_user_logged_in(): return redirect('/account') error_messages = [] data = dict() if request.method == "POST": error_messages = create_user(request) if error_messages: data["post_data"] = request.POST else: data["success"] = True data['countries'] = Helper.get_countries() data['currency'] = Helper.get_currency() data['error_messages'] = error_messages return render(request, 'register.html', data)
def search(request): status = request.POST['status'] outcome = request.POST['outcome'] start_date = request.POST['start_date'] end_date = request.POST['end_date'] min_amount = request.POST['min_amount'] max_amount = request.POST['max_amount'] error_messages = [] error_messages.extend(search_all_inputs(request)) ac = Authentication(request) user_id = ac.get_user_session() cursor = connection.cursor() results = cursor.execute( f"select * from transactions_by_state WHERE user_id = {user_id}") if not results: return [] if min_amount and max_amount: min_amount = float(min_amount) max_amount = float(max_amount) df = pd.DataFrame(results) if status: df = df.loc[df['status'] == status] if outcome: df = df.loc[df['outcome'] == outcome] if min_amount: df = df.loc[df['amount'] >= float(min_amount)] if max_amount: df = df.loc[df['amount'] <= float(max_amount)] if start_date: df = df.loc[df['created_date'] >= start_date] if end_date: df = df.loc[df['created_date'] <= end_date] return df.iterrows()
def search(request): currency = request.POST['currency'] purchase_type = request.POST['purchase_type'] closing_date = request.POST['closing_date'] min_amount = request.POST['min_amount'] max_amount = request.POST['max_amount'] error_messages = [] error_messages.extend(search_all_inputs(request)) if error_messages: return error_messages ac = Authentication(request) user_id = ac.get_user_session() cursor = connection.cursor() single_status = f"('{Status.STARTED.value}')" initial_query = f"SELECT * FROM transactions_levels_status WHERE status in {single_status} " results = cursor.execute(initial_query) if not results: return [] df = pd.DataFrame(results) df = df.loc[df['user_id'] != user_id] if currency: df = df.loc[df['currency'] == currency] if purchase_type: df = df.loc[df['purchase_type'] == purchase_type] if closing_date: df = df.loc[df['end_time'] <= closing_date] if min_amount: df = df.loc[df['amount'] >= float(min_amount)] if max_amount: df = df.loc[df['amount'] <= float(max_amount)] return df.iterrows()
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 login(request): data = {} ac = Authentication(request) # if user is logged in redirect to account page if ac.is_user_logged_in(): return redirect('/account') if request.method == "POST": email = request.POST['email'] password = request.POST['password'] error_messages = validate_login_inputs(email, password) if not error_messages: # encrypt user enter password in the login page to check with db password password_encrypted = Helper.password_encrypt(password) cursor = connection.cursor() # check whether user exists in the DB user = cursor.execute( "SELECT * FROM user_credential where email =" + "'" + email + "' ") if user and user[0]['password'] == Helper.password_encrypt( password): # get loged user details q = f"SELECT * FROM user_by_id where id = {user[0]['id']}" user = cursor.execute(q) # create user session and store user id ac.save_user_session(str(user[0]['id'])) return redirect('/account') error_messages.append("Invalid email or password") data["error_messages"] = error_messages return render(request, 'login.html', 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 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 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']))