Exemplo n.º 1
0
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(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"]))
Exemplo n.º 3
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 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 get_filtered_chart_data(user_id, start_date, end_date, stat_key):
    cursor = connection.cursor()

    result = []
    if not start_date:
        return Helper.get_json_response(False, dict(), ['Please select a start date'])
    if start_date and not end_date:
        result = cursor.execute(f"SELECT * FROM states WHERE user_id = {user_id} "
                                f"AND type = '{stat_key}'and date >= '{start_date}'")
    if start_date and end_date:
        result = cursor.execute(f"SELECT * FROM states WHERE user_id = {user_id} "
                                f"AND type = '{stat_key}'and date >= '{start_date}' "
                                f"and date <= '{end_date}'")

    if result:
        response = dict()
        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[stat_key] = item
        return Helper.get_json_response(True, response, [''])
    return Helper.get_json_response(False, dict(), ['Data not available for this range'])
def get_chart_by_state_keys(user_id, key_list, start_date, end_date):
    cursor = connection.cursor()
    response = dict()
    result = []
    for stat_key in key_list:
        if not start_date:
            return Helper.get_json_response(False, dict(), ['Please select a start date'])
        if start_date and not end_date:
            result = cursor.execute(f"SELECT * FROM states WHERE user_id = {user_id} "
                                    f"AND type = '{stat_key}'and date >= '{start_date}'")
        if start_date and end_date:
            result = cursor.execute(f"SELECT * FROM states WHERE user_id = {user_id} "
                                    f"AND type = '{stat_key}'and date >= '{start_date}' "
                                    f"and date <= '{end_date}'")

        item = dict()
        item['date'] = json.dumps([])
        item['value'] = json.dumps([])
        response[stat_key] = item
        if result:
            df = pd.DataFrame(result)
            item['date'] = df['date'].astype(str).to_json(orient='records')
            item['value'] = df['value'].astype(float).to_json(orient='records')
            response[stat_key] = item
    return Helper.get_json_response(True, response, [])
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 get_forecast(request):
    post = request.POST
    currency_pair = post["currency_pair"]
    data = dict()
    cursor = connection.cursor()
    today_date = Helper.get_today_date()
    result = cursor.execute(
        f"SELECT * FROM forecast WHERE currency_pair = '{currency_pair}' AND "
        f"date > '{today_date}'")
    result = result.all()
    if result:
        df = pd.DataFrame(result)
        data["date"] = df['date'].astype(str).to_json(orient='records')
        data["value"] = df['value'].astype(float).to_json(orient='records')
        return JsonResponse(Helper.get_json_response(True, data, []))
    return JsonResponse(Helper.get_json_response(False, {}, []))
Exemplo n.º 9
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], []))
Exemplo n.º 10
0
def get_history(currency, timeframe, price_type, chart_type):
    start_date = ""
    end_date = ""
    if timeframe == 'ticks':
        start_date = Helper.get_time_formatted(datetime.now() -
                                               timedelta(hours=3))
        end_date = Helper.get_time_formatted(datetime.now())
        table = "forex_pip_data"

    if timeframe == 'minute':
        start_date = Helper.get_time_formatted(datetime.now() -
                                               timedelta(days=3))
        end_date = Helper.get_time_formatted(datetime.now())
        table = "forex_data"

    if timeframe == 'five_min':
        start_date = Helper.get_time_formatted(datetime.now() -
                                               timedelta(days=3))
        end_date = Helper.get_time_formatted(datetime.now())
        table = "forex_data_five_min"

    if timeframe == 'fifteen_min':
        start_date = Helper.get_time_formatted(datetime.now() -
                                               timedelta(days=4))
        end_date = Helper.get_time_formatted(datetime.now())
        table = "forex_data_fifteen_min"

    if timeframe == 'thirty_min':
        start_date = Helper.get_time_formatted(datetime.now() -
                                               timedelta(days=10))
        end_date = Helper.get_time_formatted(datetime.now())
        table = "forex_data_thirty_min"

    if timeframe == 'hour':
        start_date = Helper.get_time_formatted(datetime.now() -
                                               timedelta(days=15))
        end_date = Helper.get_time_formatted(datetime.now())
        table = "forex_data_one_hour"

    if timeframe == 'four_hours':
        start_date = Helper.get_time_formatted(datetime.now() -
                                               timedelta(days=15))
        end_date = Helper.get_time_formatted(datetime.now())
        table = "forex_data_four_hours"

    if timeframe == 'one_day':
        start_date = Helper.get_time_formatted(datetime.now() -
                                               timedelta(days=100))
        end_date = Helper.get_time_formatted(datetime.now())
        table = "forex_data_one_day"

    cursor = connection.cursor()
    result = cursor.execute(
        f"SELECT * FROM {table} WHERE currency_pair = '{currency}' "
        f"and timestamp > '{start_date}' AND timestamp < '{end_date}'")

    if not result:
        return JsonResponse(
            Helper.get_json_response(False, {}, ["Data Not available"]))

    df = pd.DataFrame(result)
    df = df.sort_values(by='timestamp', ascending=True)
    timestamp = df['timestamp'].astype(str).to_json(orient='records')
    data = dict()
    if chart_type == "line":
        if price_type == "close":
            close = df['close'].to_json(orient='records')

            data["timestamp"] = timestamp
            data["close"] = close

        if price_type == "open":
            open_price = df['open'].to_json(orient='records')

            data["timestamp"] = timestamp
            data["open"] = open_price

        if price_type == "high":
            high = df['high'].to_json(orient='records')

            data["timestamp"] = timestamp
            data["high"] = high

        if price_type == "low":
            low = df['low'].to_json(orient='records')
            data["timestamp"] = timestamp
            data["low"] = low

    if chart_type == "candlestick":
        close = df['close'].to_json(orient='records')
        open_price = df['open'].to_json(orient='records')
        high = df['high'].to_json(orient='records')
        low = df['low'].to_json(orient='records')

        data["timestamp"] = timestamp
        data["close"] = close
        data["open"] = open_price
        data["high"] = high
        data["low"] = low

    return JsonResponse(Helper.get_json_response(True, data, []))
Exemplo n.º 11
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']))