示例#1
0
def supplier_control_limits_put():
    currencies_config = request.json['data']

    def is_brl_ok(config):
        return is_positive_number(config.get('SettlementRate', None))

    def is_ccy_ok(ccy, config):
        return (is_positive_number(config.get('SettlementRate', None))
                and is_positive_number(config.get('MaxQuantity', None))
                and is_positive_number(config.get('MarkupBUY', None), ge=True)
                and is_positive_number(config.get('MarkupSELL', None),
                                       ge=True))

    ccy_valid = False
    system_currencies = databus.get('Currencies')
    if set(system_currencies) != set(currencies_config.keys()):
        return jsonify({'status': 'error - invalid_uploaded_data'
                        })  # TODO: melhorar mensagem

    for ccy, config in currencies_config.items():
        if ccy.lower() == 'brl':
            ccy_valid = is_brl_ok(config)
        else:
            ccy_valid = is_ccy_ok(ccy, config)

        if not ccy_valid:
            return jsonify({'status': 'error - invalid_uploaded_data'})

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

    databus.update_from_file(get_data_path('RobotFX_FXSupplierControl.json'),
                             'FXSupplierControl')
    return jsonify({'status': 'ok'})
示例#2
0
def engine_parameters_ndf_put():
    engine_parameters = json.loads(request.data)
    status = 'ok'
    try:
        datetime.datetime.strptime(
            engine_parameters['engine_parameters']['EngineOnlineEndTime'],
            "%H:%M")
    except ValueError:
        status = 'ok - Not a valid date.'

    if status == 'ok':
        with open(
                get_data_path('RobotFX_TradingParameters.json')) as json_file:
            old_obj = json.load(json_file)
            old_obj["Engine_Global_Parameters"]["FXNDF"] = engine_parameters[
                'engine_parameters']

        with open(get_data_path('RobotFX_TradingParameters.json'),
                  "w") as json_file_out:
            json_file_out.write(json.dumps(old_obj, sort_keys=True, indent=4))

        databus.update_from_file(
            get_data_path('RobotFX_TradingParameters.json'),
            'TradingParameters')

    return jsonify({'status': status})
示例#3
0
def group_put():
    try:
        json_req_data = json.loads(request.data)
        group = json_req_data['group']
        alias = json_req_data['alias']

        with open(get_data_path('RobotFX_LegalEntitiesRelationships.json')) as json_file:
            groups_data = json.load(json_file)
            work_data = groups_data["Groups_Spreads"]['FX' + group['Type']]

            # Se for o update de um grupo existente
            if group['Alias'] == alias:
                work_data[alias]["Name"] = group["Name"]
            else:
                alias = group['Alias']
                work_data[alias] = {'Name': group['Name']}

            groups_data["Groups_Spreads"]['FX' + group['Type']] = work_data

        with open(get_data_path('RobotFX_LegalEntitiesRelationships.json'), "w") as json_file_out:
            json_file_out.write(json.dumps(groups_data, indent=2))

        databus.update_from_file(get_data_path('RobotFX_LegalEntitiesRelationships.json'), 'LegalEntitiesRelationships')

        return jsonify({'status': 'ok'})
    except KeyError:
        exc_info = sys.exc_info()
        return jsonify({'status': 'error', 'exception': ''.join(traceback.format_exception(*exc_info))})
示例#4
0
def put_time_buckets():
    time_buckets = request.json['time_buckets']
    with open(get_data_path('RobotFX_NDFTimeBuckets.json')) as json_file:
        time_buckets_data = json.load(json_file)
        time_buckets_data['TimeBuckets'] = time_buckets

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

    databus.update_from_file(get_data_path('RobotFX_NDFTimeBuckets.json'), 'NDFTimeBuckets')

    return jsonify({'status': 'ok'})
示例#5
0
def cutoff_times_spot_put():
    json_data = json.loads(request.data)
    cutoff_times_spot = json_data['cutoff_times']
    with open(get_data_path('RobotFX_SpotConfig.json')) as json_file:
        old_obj = json.load(json_file)
        old_obj["CutOffTimes"] = cutoff_times_spot

    with open(get_data_path('RobotFX_SpotConfig.json'), "w") as json_file_out:
        json_file_out.write(json.dumps(old_obj, indent=2))

    databus.update_from_file(get_data_path('RobotFX_SpotConfig.json'),
                             'SpotConfig')

    return jsonify({'status': 'ok'})
示例#6
0
def currency_keys_spot_put():
    currency_keys = json.loads(request.data)
    with open(get_data_path('RobotFX_TradingParameters.json')) as json_file:
        old_obj = json.load(json_file)
        old_obj["CurrencyKeys"] = currency_keys['currency_keys']

    with open(get_data_path('RobotFX_TradingParameters.json'),
              "w") as json_file_out:
        json_file_out.write(json.dumps(old_obj, sort_keys=True, indent=4))

    databus.update_from_file(get_data_path('RobotFX_TradingParameters.json'),
                             'TradingParameters')

    return jsonify({'status': 'ok'})
示例#7
0
def currencies_put():
    try:
        currencies = json.loads(request.data)['currencies']

        with open(get_data_path('RobotFX_Currencies.json'), "w") as json_file_out:
            json_file_out.write(json.dumps(currencies, indent=2))

        databus.update_from_file(get_data_path('RobotFX_Currencies.json'), 'Currencies')

        return jsonify({'status': 'ok'})
    except KeyError:
        exc_info = sys.exc_info()
        return jsonify({'status': 'error', 'exception': ''.join(traceback.format_exception(*exc_info))})
    except json.decoder.JSONDecodeError:
        return jsonify({'status': 'fail'})
示例#8
0
def engine_parameters_spot_put():
    try:
        engine_parameters = json.loads(request.data)
        with open(
                get_data_path('RobotFX_TradingParameters.json')) as json_file:
            old_obj = json.load(json_file)
            old_obj["Engine_Global_Parameters"]["FXSPOT"] = engine_parameters[
                'engine_parameters']

        with open(get_data_path('RobotFX_TradingParameters.json'),
                  "w") as json_file_out:
            json_file_out.write(json.dumps(old_obj, sort_keys=True, indent=4))

        databus.update_from_file(
            get_data_path('RobotFX_TradingParameters.json'),
            'TradingParameters')

        return jsonify({'status': 'ok'})
    except json.decoder.JSONDecodeError:  # caso uso do comando: curl...
        return jsonify({'status': 'fail'})
    except Exception:
        return jsonify({'status': 'fail'})
示例#9
0
def casado_data_put():
    casado_config = request.json['data']

    if not casado_config or not is_positive_number(casado_config):
        return jsonify({'status': 'error - invalid_uploaded_data'})

    with open(get_data_path('RobotFX_FXSupplierCasado.json')) as json_file:
        casado_data = json.load(json_file)

        try:
            casado_data['Price'] = float(casado_config)
        except ValueError:
            return jsonify(
                {'status': "error: casado price's data is invalid!"})

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

    databus.update_from_file(get_data_path('RobotFX_FXSupplierCasado.json'),
                             'FXSupplierCasado')

    return jsonify({'status': 'ok'})
示例#10
0
def counterparty_config_put():
    try:
        cp = json.loads(request.data)['counterparty']
        cnpj = cp['Cnpj']
        del cp['Cnpj']
        sel_spot = json.loads(request.data)['selected_spot']
        sel_ndf = json.loads(request.data)['selected_ndf']
        update_case = json.loads(request.data)['update_case']

        if "FXSPOT" not in cp['Products']:
            cp['FXMarketType'] = 1
            cp['DefaultFXTransaction'] = ''
            sel_spot = ''

        if "FXNDF" not in cp['Products']:
            sel_ndf = ''

        with open(get_data_path('RobotFX_LegalEntities.json')) as json_file:
            old_obj = json.load(json_file)
            if not update_case and cnpj in old_obj:
                return jsonify({'status': 'already_taken'})

            old_obj[cnpj] = cp

        with open(get_data_path('RobotFX_LegalEntities.json'), "w") as json_file_out:
            json_file_out.write(json.dumps(old_obj, indent=2))

        databus.update_from_file(get_data_path('RobotFX_LegalEntities.json'), 'LegalEntities')

        with open(get_data_path('RobotFX_TradingParameters.json')) as json_file:
            old_obj = json.load(json_file)
            cp = old_obj['CounterpartyKeys']

        with open(get_data_path('RobotFX_TradingParameters.json'), "w") as json_file_out:
            new_counterparty_default = {
                cnpj: {
                    "FXSPOT": {"ValidateKYC": "YES", "AutoFlow": "ENABLED"},
                    "FXNDF": {
                        "UpperLimitDays2Maturity": 720,
                        "AutoFlow": "ENABLED",
                        "ValidateKYC": "YES",
                        "ValidateISDA": "YES",
                    },
                }
            }
            cp.update(new_counterparty_default)
            old_obj['CounterpartyKeys'] = cp
            json_file_out.write(json.dumps(old_obj, sort_keys=True, indent=4))

        databus.update_from_file(get_data_path('RobotFX_TradingParameters.json'), 'TradingParameters')

        currencies = list(databus.get_dict('Currencies').keys())
        currencies.remove('BRL')

        time_buckets = []
        with open(get_data_path('RobotFX_NDFTimeBuckets.json')) as json_file:
            old_obj = json.load(json_file)
            tb = old_obj['TimeBuckets']
            for elem in tb:
                time_buckets.append(elem['EndDay'])

        with open(get_data_path('RobotFX_Client_Spreads.json')) as json_file:
            old_client_spreads = json.load(json_file)
            old_client_spreads['CounterpartySpreads'][cnpj] = {
                'FXSPOT': {},
                'FXNDF': {'Buckets': time_buckets, 'Spreads': {}},
            }
            for cur in currencies:
                old_client_spreads['CounterpartySpreads'][cnpj]['FXSPOT'][cur] = {'BUY': [None] * 3, 'SELL': [None] * 3}
                old_client_spreads['CounterpartySpreads'][cnpj]['FXNDF']['Spreads'][cur] = {
                    'BUYSELL': [None] * len(time_buckets)
                }

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

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

        with open(get_data_path('RobotFX_LegalEntitiesRelationships.json')) as json_file:
            groups_data = json.load(json_file)
            groups_data["Groups_Spreads_FXSPOT_Memberships"][cnpj] = sel_spot
            groups_data["Groups_Spreads_FXNDF_Memberships"][cnpj] = sel_ndf

        with open(get_data_path('RobotFX_LegalEntitiesRelationships.json'), "w") as json_file_out:
            json_file_out.write(json.dumps(groups_data, indent=2))

        databus.update_from_file(get_data_path('RobotFX_LegalEntitiesRelationships.json'), 'LegalEntitiesRelationships')

        return jsonify({'status': 'ok'})
    except KeyError:
        exc_info = sys.exc_info()
        return jsonify({'status': 'error', 'exception': ''.join(traceback.format_exception(*exc_info))})
    except json.decoder.JSONDecodeError:
        return jsonify({'status': 'fail because JSONDecoderError!'})
示例#11
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'})
示例#12
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'})