Пример #1
0
def update_balance_ndf(ccy, amount_ccy, amount_pv, amount_brl, revenue_brl, side, dc):
    def incr_by(key, value):
        db_key = f'Balance/NDF/{ccy}/{key}'
        databus.increase_by_float(db_key, value)

    incr_by('TotalAmount', amount_ccy)
    incr_by('NetPV', amount_pv)
    incr_by('NetPV_BRL', amount_brl)
    incr_by('NetAmount', amount_ccy if side.lower() == 'buy' else -amount_ccy)
    incr_by('Revenue_BRL', revenue_brl)
    incr_by(f'{side}/TotalPV', amount_pv)
    incr_by(f'{side}/TotalAmount', abs(amount_ccy))

    partial_pv_key = f'Balance/NDF/{ccy}/{side}/PartialPV'
    partial_pv_list = databus.get(partial_pv_key)
    tuple_partial_pvs_max_dcs = (1, 31, 61, 91, 181, 361, 721)
    idx = bisect.bisect_right(tuple_partial_pvs_max_dcs, dc) - 1
    partial_pv_list[idx] += amount_pv
    databus.set(partial_pv_key, partial_pv_list)

    partial_amount_key = f'Balance/NDF/{ccy}/{side}/PartialAmount'
    partial_amount_list = databus.get(partial_amount_key)
    idx = bisect.bisect_right(tuple_partial_pvs_max_dcs, dc) - 1
    partial_amount_list[idx] += abs(amount_ccy)
    databus.set(partial_amount_key, partial_amount_list)
Пример #2
0
def update_validate_rule(validate_rule, system_keyword, cnpj, is_ndf):
    rfq_type = "NDF" if is_ndf else "SPOT"
    if validate_rule.startswith('NO: GOOD-TODAY'):
        rule_date_str = validate_rule.split("|")[1]
        rule_date = np.datetime64(rule_date_str)
        today_str = get_today_str()
        today = np.datetime64(today_str)
        if rule_date != today:
            databus_key = f"TradingParameters/CounterpartyKeys/{cnpj}/FX{rfq_type}/Validate{system_keyword}"
            databus.set(databus_key, 'YES')
            return 'YES'
        else:
            return 'NO: GOOD-TODAY'
    else:
        return validate_rule
Пример #3
0
def pre_trading_ini_bal_spot_put():
    pre_trading_ini_bal_spot = json.loads(request.data)['pre_trading_ini_bal']

    initialized = False
    log = {}

    for ccy, maturity_balance in pre_trading_ini_bal_spot.items():
        log[ccy] = {}
        for maturity, value in maturity_balance.items():
            log[ccy][maturity] = [value]
            if value is not None:
                initialized = True

    databus.update_from_dict(pre_trading_ini_bal_spot, 'CashLimits/SPOT')
    databus.update_from_dict(log, 'CashLimits/Logs')
    databus.set('System/Status/Trading/SPOT/Initialized', initialized)

    return jsonify({'status': 'ok'})
Пример #4
0
def pre_trading_balance_update():
    """
@login_required(roles=['e-sales spot'])
    atualiza o CashLimits adicionando ou removendo + dinheiro.
    """
    balance_update = json.loads(request.data)
    balance_update = balance_update.get('balance_update', None)

    if balance_update is not None:
        for ccy, limits in balance_update.items():
            for maturity, value in limits.items():
                if value is None:
                    continue

                value = float(value)
                n = int(maturity[1])

                if n not in [0, 1]:
                    continue

                if databus.get(f'CashLimits/SPOT/{ccy}/{maturity}') is None:
                    databus.set(f'CashLimits/SPOT/{ccy}/{maturity}', 0.0)

                if value > 0:
                    success, error_msg = increase_cash_limits_spot(
                        ccy, value, n)
                else:
                    success, error_msg = decrease_cash_limits_spot(ccy,
                                                                   value,
                                                                   n,
                                                                   reset=True)

                ccy_logs = databus.get(f'CashLimits/Logs/{ccy}/{maturity}')
                if isinstance(ccy_logs, list):
                    ccy_logs.append(value)
                    databus.set(f'CashLimits/Logs/{ccy}/{maturity}', ccy_logs)

                if not success:
                    return jsonify({'status': 'fail', 'reason': error_msg})

    return jsonify({'status': 'ok'})
Пример #5
0
def login():
    if request.method == 'POST':
        req_data = request.form
        username = req_data.get('username', '').lower()
        if not username:
            session["login_error_msg"] = "Incorrect username or password."
            return redirect(url_for("auth_bp.login"))

        # hidden_login_code = req_data.get('hidden_login_code', '')
        # hidden_login_code_databus_key = "HiddenLoginCode"
        # hidden_login_code_in_databus = databus.get(hidden_login_code_databus_key)
        # if hidden_login_code != hidden_login_code_in_databus:
        #     session["login_error_msg"] = "Incorrect username or password."
        #     return redirect(url_for("auth_bp.login"))

        try:
            with open('/home/duanribeiro/PycharmProjects/exemplo_flask_decorator/data/RobotFX_Users.json') as json_file:
                file_dict = json.load(json_file)

                if username not in file_dict:
                    session["login_error_msg"] = "Incorrect username or password."
                    return redirect(url_for("auth_bp.login"))

                user_data = file_dict[username]

                hash_pwd = user_data['password']
                password = req_data.get('password', '')
                if not check_password_hash(hash_pwd, password):
                    session["login_error_msg"] = "Incorrect username or password."
                    return redirect(url_for("auth_bp.login"))

                redirct_url_dic = {
                    "e-sales ndf": "fxndf_bp.blotter_ndf",
                    "e-sales spot": "fxspot_bp.blotter_spot",
                    "ti": "log_bp.log",
                    "si": "auth_bp.user_management",
                    "fx-supplier": "fxsupplier_bp.supplier_control",
                    "supervisor": "fxspot_bp.statistics_spot",
                }

                user_id = str(uuid.uuid4())
                user_id_databus_key = f"ActiveUsers/{user_id}"
                databus.set(user_id_databus_key, user_id)
                session["user_id"] = user_id

                user_role = user_data["role"]
                user_role_databus_key = f"ActiveUsers/{user_id}/Role"
                databus.set(user_role_databus_key, user_role)
                session["role"] = user_role

                username_databus_key = f"ActiveUsers/{user_id}/Username"
                databus.set(username_databus_key, username)
                session["username"] = username

                # databus.delete(hidden_login_code_databus_key)
                # return redirect(url_for(redirct_url_dic[user_role]))
                return {"user_id": user_id}

        except Exception:
            session["login_error_msg"] = "Incorrect username or password."
            return redirect(url_for('auth_bp.login'))

    hidden_login_code = str(uuid.uuid4())
    # hidden_login_code = '123'
    # hidden_login_code_databus_key = "HiddenLoginCode"
    # databus.set(hidden_login_code_databus_key, hidden_login_code)
    login_error_msg = session.get('login_error_msg', None)
    session.pop('login_error_msg', None)
    return render_template('login.html', hidden_login_code=hidden_login_code, login_error_msg=login_error_msg)
Пример #6
0
def spreads_spot_put():
    now = get_local_time()
    type_update = request.args.get('type', '').lower()
    update_group = type_update == 'group'
    key = request.args.get('key', '').upper()
    status = request.json['status']
    currency = status['currency']
    spotDay = status['spotday']
    side = status['side']
    spread = status['spread']
    if spread != '-':
        spread = int(
            Decimal(spread) *
            10_000)  # Solucao de caso de spread igual a: 12, 24 ou 48.

    basic_key = 'SpreadRegistry/SPOT/' + type_update

    if databus.exists(basic_key):
        data_list = databus.get(basic_key)
    else:
        data_list = []
    user_id = session.get("user_id", None)
    username = get_username(user_id)
    element = {
        'target': key,
        'ts': now.strftime('%Y-%m-%d %H:%M:%S'),
        'user': str(username),
        'ccy': str(currency),
        'spotday': str(spotDay),
        'side': str(side),
        'spread': str(spread),
    }

    if not update_group:
        element['counterparty'] = databus.get(
            'LegalEntities/{cnpj}/CounterpartyName'.format(cnpj=key))
        basic_group_key = 'LegalEntitiesRelationships/Groups_Spreads_'
        if databus.exists((basic_group_key +
                           'FX{type}_Memberships/{cnpj}').format(cnpj=key,
                                                                 type='SPOT')):
            element['group'] = databus.get(
                (basic_group_key + 'FX{type}_Memberships/{cnpj}').format(
                    cnpj=key, type="SPOT"))
        else:
            element['group'] = '-'

    data_list.append(element)

    databus.set(basic_key, data_list)

    manage_spreads_tables(1, is_ndf=False)

    with open(get_data_path('RobotFX_Client_Spreads.json')) as json_file:
        all_spreads = json.load(json_file)
        entity_type = 'GroupSpreads' if update_group else 'CounterpartySpreads'
        if key not in all_spreads[entity_type]:
            all_spreads[entity_type][key] = {}

        all_spreads[entity_type][key]['FXSPOT'] = request.json['spreads']

    with open(get_data_path('RobotFX_Client_Spreads.json'),
              'w') as json_file_out:
        json_file_out.write(json.dumps(all_spreads, indent=2))

    databus.update_from_file(get_data_path('RobotFX_Client_Spreads.json'),
                             'ClientSpreads')

    return jsonify({'status': 'ok'})
Пример #7
0
def set_local_datetime(new_datetime):
    now = datetime.now()
    delta = now - new_datetime
    databus.set("TodayDelta", delta.total_seconds())
Пример #8
0
def spreads_ndf_put():
    now = get_local_time()
    print('ndf put.....')
    type_update = request.args.get('type', '').lower()
    update_group = type_update == 'group'
    key = request.args.get('key', '').upper()
    if 'status' not in request.json:
        return jsonify({
            'status':
            'error',
            'exception':
            'Status data is not in Request\'s JSON\'s Content.'
        })

    status = request.json['status']
    if ('currency' in status) and ('bucket' in status) and ('spread'
                                                            in status):
        currency = status['currency']
        bucket = status['bucket']
        spread = status['spread']
        if spread is None:
            spread = '-'

        if spread != '-':
            spread = int(
                Decimal(spread) *
                10_000)  # Solucao de caso de spread igual a: 12, 24 ou 48.

        basic_key = 'SpreadRegistry/NDF/' + type_update

        if databus.exists(basic_key):
            data_list = databus.get(basic_key)
        else:
            data_list = []

        user_id = session.get("user_id", None)
        username = get_username(user_id)
        element = {
            'target': key,
            'ts': now.strftime('%Y-%m-%d %H:%M:%S'),
            'user': str(username),
            'ccy': str(currency),
            'bucket': str(bucket),
            'spread': str(spread),
        }

        if not update_group:
            element['counterparty'] = databus.get(
                'LegalEntities/{cnpj}/CounterpartyName'.format(cnpj=key))
            basic_group_key = 'LegalEntitiesRelationships/Groups_Spreads_'
            if databus.exists(
                (basic_group_key + 'FX{type}_Memberships/{cnpj}').format(
                    cnpj=key, type='NDF')):
                element['group'] = databus.get(
                    (basic_group_key + 'FX{type}_Memberships/{cnpj}').format(
                        cnpj=key, type="NDF"))
            else:
                element['group'] = '-'

        data_list.append(element)

        databus.set(basic_key, data_list)

        manage_spreads_tables(1, is_ndf=True)

    with open(get_data_path('RobotFX_Client_Spreads.json')) as json_file:
        all_spreads = json.load(json_file)
        entity_type = 'GroupSpreads' if update_group else 'CounterpartySpreads'
        if key not in all_spreads[entity_type]:
            all_spreads[entity_type][key] = {}

        all_spreads[entity_type][key]['FXNDF'] = request.json[
            'spreads_catalog']

    with open(get_data_path('RobotFX_Client_Spreads.json'),
              'w') as json_file_out:
        json_file_out.write(json.dumps(all_spreads, indent=2))

    databus.update_from_file(get_data_path('RobotFX_Client_Spreads.json'),
                             'ClientSpreads')

    return jsonify({'status': 'ok'})