Exemplo n.º 1
0
def fast_refresh():

    df = pd.DataFrame()
    dddd = pd.DataFrame()
    dfs = pd.DataFrame()
    final = pd.DataFrame()
    dfs2 = pd.DataFrame()
    result = pd.DataFrame()
    filter = pd.DataFrame()
    alfa_bd = pd.DataFrame()
    alfa_bd2 = pd.DataFrame()
    hot_bd2 = pd.DataFrame()
    live_bd2 = pd.DataFrame()
    live_bd = pd.DataFrame()
    hot_bd = pd.DataFrame()

    alfa_bd = pd.read_csv(main_path_data + "\\alfa_bd_PU.csv", thousands=',')
    alfa_bd2 = pd.read_csv(main_path_data + "\\alfa_bd_PB.csv", thousands=',')

    hot_bd2 = pd.read_csv(main_path_data + "\\hot_bd_PB.csv", thousands=',')
    live_bd2 = pd.read_csv(main_path_data + "\\live_bd_PB.csv", thousands=',')
    try:
        with open(main_path_data + "\\live_bd_PU.csv", 'r') as f:
            live_bd = pd.read_csv(f, thousands=',')
            f.close()
    except Exception as e:
        with open(main_path_data + "\\live_bd_PU.csv", 'r') as f:
            live_bd = pd.read_csv(f, thousands=',')
            f.close()

    try:
        with open(main_path_data + "\\hot_bd_PU.csv", 'r') as f:
            hot_bd = pd.read_csv(f, thousands=',')
            f.close()
    except Exception as e:
        print("EXCEPT to open HOT")
        time.sleep(0.1)
        with open(main_path_data + "\\hot_bd_PU.csv", 'r') as f:
            hot_bd = pd.read_csv(f, thousands=',')
            f.close()
            pass

    new_regims_f = open(second_path_data + "\\new_regims.json", 'r')
    new_regims = json.load(new_regims_f)
    new_regims_f.close()

    bal = pd.read_csv(second_path_data + "\\balance.csv")
    balances2 = bal.to_json(orient='records')
    balances = json.loads(balances2)

    new_com = open(second_path_data + "\\commis.json", 'r')
    com = json.load(new_com)
    new_com.close()

    frames = [alfa_bd, hot_bd, live_bd, alfa_bd2, hot_bd2, live_bd2]
    df = pd.concat(frames, ignore_index=True)

    filter_a = df[df['birga'] == 'alfa'].index
    filter_l = df[df['birga'] == 'live'].index
    filter_h = df[df['birga'] == 'hot'].index

    a = com['main']["alfa"]
    l = com['main']["live"]
    h = com['main']["hot"]

    df.loc[(filter_a), 'Com'] = float(a)
    df.loc[(filter_h), 'Com'] = float(h)
    df.loc[(filter_l), 'Com'] = float(l)

    dfs2 = pd.merge(df,
                    df,
                    left_on=df['valout'],
                    right_on=df['valin'],
                    how='outer')
    dfs2['rates_x'] = dfs2['rates_x'].replace(',', '', regex=True).apply(
        pd.to_numeric, errors='coerce')
    dfs2['rates_y'] = dfs2['rates_y'].replace(',', '', regex=True).apply(
        pd.to_numeric, errors='coerce')
    dfs2['volume_x'] = dfs2['volume_x'].replace(',', '', regex=True).apply(
        pd.to_numeric, errors='coerce')
    dfs2['volume_y'] = dfs2['volume_y'].replace(',', '', regex=True).apply(
        pd.to_numeric, errors='coerce')
    dfs2.drop(['key_0'], axis=1, inplace=True)
    dfs2['rates_y'] = dfs2['rates_y'].map('{:,.10f}'.format)
    dfs2['rates_x'] = dfs2['rates_x'].map('{:,.10f}'.format)

    ###############       Main dataframe with all data      ####################
    result = dfs2[(dfs2['valin_x'] == dfs2['valout_y'])]
    usdt = dfs2[(dfs2['valin_x'] == 'USD') & (dfs2['valout_y'] == 'USDT')]
    usd = dfs2[(dfs2['valin_x'] == 'USDT') & (dfs2['valout_y'] == 'USD')]
    final = result.append([usdt, usd])
    final.reset_index(inplace=True, drop=True)
    final.reset_index(level=0, inplace=True)
    filter = final[(final['birga_x'] == final['birga_y'])
                   & (final['rates_x'] < final['rates_y']) &
                   (final['valin_x'] == final['valout_y'])]

    final = final.drop(filter['index'], axis=0)

    final['rates_x'] = final['rates_x'].replace(',', '', regex=True).apply(
        pd.to_numeric, errors='coerce')
    final['rates_y'] = final['rates_y'].replace(',', '', regex=True).apply(
        pd.to_numeric, errors='coerce')
    final['volume_x'] = final['volume_x'].replace(',', '', regex=True).apply(
        pd.to_numeric, errors='coerce')
    final['volume_y'] = final['volume_y'].replace(',', '', regex=True).apply(
        pd.to_numeric, errors='coerce')
    final['Com_x'] = final['Com_x'].replace(',', '',
                                            regex=True).apply(pd.to_numeric,
                                                              errors='coerce')
    final['Com_y'] = final['Com_y'].replace(',', '',
                                            regex=True).apply(pd.to_numeric,
                                                              errors='coerce')

    for i in balances:
        balanc_a = final[(final['birga_x'] == 'alfa')
                         & (final['valin_x'] == i['Valuta'])].index
        balanc_h = final[(final['birga_x'] == 'hot')
                         & (final['valin_x'] == i['Valuta'])].index
        balanc_l = final[(final['birga_x'] == 'live')
                         & (final['valin_x'] == i['Valuta'])].index

        a_b = i['alfa']
        h_b = i['hot']
        l_b = i['live']

        final.loc[(balanc_a), 'Bal1'] = a_b / final.loc[(balanc_a), 'rates_x']
        final.loc[(balanc_h), 'Bal1'] = h_b / final.loc[
            (balanc_h), 'rates_x'] - (h_b / final.loc[(balanc_h), 'rates_x'] *
                                      final.loc[(balanc_h), 'Com_x'] / 100)
        final.loc[(balanc_l), 'Bal1'] = l_b / final.loc[
            (balanc_l), 'rates_x'] - (l_b / final.loc[(balanc_l), 'rates_x'] *
                                      final.loc[(balanc_l), 'Com_x'] / 100)

        balanc_a2 = final[(final['birga_y'] == 'alfa')
                          & (final['valin_y'] == i['Valuta'])].index
        balanc_h2 = final[(final['birga_y'] == 'hot')
                          & (final['valin_y'] == i['Valuta'])].index
        balanc_l2 = final[(final['birga_y'] == 'live')
                          & (final['valin_y'] == i['Valuta'])].index

        final.loc[(balanc_a2), 'Bal2'] = a_b
        final.loc[(balanc_h2), 'Bal2'] = h_b
        final.loc[(balanc_l2), 'Bal2'] = l_b

    reg2 = final
    final.loc[:, "volume"] = final[['volume_x', 'volume_y', 'Bal2',
                                    'Bal1']].min(axis=1)

    final['volume'] = final['volume'].map('{:,.10f}'.format)
    final['volume'] = final['volume'].replace(',', '', regex=True).apply(
        pd.to_numeric, errors='coerce')

    final.loc[:, 'Vol1'] = final['rates_x'] * final['volume'] + (
        final['rates_x'] * final['volume'] * final['Com_x'] / 100)
    final.loc[:, 'Vol2'] = final['volume']
    final.loc[:, 'Vol3'] = final['volume']
    final.loc[:, 'Vol4'] = final['rates_y'] * final['volume'] - (
        final['rates_y'] * final['volume'] * final['Com_y'] / 100)

    fil_a = final[final['birga_x'] == 'alfa'].index
    final.loc[(fil_a), 'Vol3'] = final.loc[(fil_a), 'Vol2'] - (final.loc[
        (fil_a), 'Vol2'] * final.loc[(fil_a), 'Com_x'] / 100)
    final.loc[(fil_a),
              'Vol1'] = final.loc[(fil_a), 'rates_x'] * final.loc[(fil_a),
                                                                  'volume']
    final.loc[(fil_a), 'Vol4'] = final.loc[(fil_a), 'rates_y'] * final.loc[
        (fil_a), 'Vol3'] - (final.loc[(fil_a), 'rates_y'] *
                            final.loc[(fil_a), 'Vol3'] * final['Com_y'] / 100)

    final['Vol1'] = final['Vol1'].map('{:,.10f}'.format)
    final['Vol2'] = final['Vol2'].map('{:,.10f}'.format)
    final['Vol3'] = final['Vol3'].map('{:,.10f}'.format)
    final['Vol4'] = final['Vol4'].map('{:,.10f}'.format)

    final['Vol1'] = final['Vol1'].replace(',', '',
                                          regex=True).apply(pd.to_numeric,
                                                            errors='coerce')
    final['Vol2'] = final['Vol2'].replace(',', '',
                                          regex=True).apply(pd.to_numeric,
                                                            errors='coerce')
    final['Vol3'] = final['Vol3'].replace(',', '',
                                          regex=True).apply(pd.to_numeric,
                                                            errors='coerce')
    final['Vol4'] = final['Vol4'].replace(',', '',
                                          regex=True).apply(pd.to_numeric,
                                                            errors='coerce')

    final.loc[:, 'profit'] = final['Vol4'] - final['Vol1']
    final.loc[:, 'percent'] = final['profit'] / final['Vol1'] * 100

    final['profit'] = final['profit'].replace(',', '', regex=True).apply(
        pd.to_numeric, errors='coerce')
    final['percent'] = final['percent'].replace(',', '', regex=True).apply(
        pd.to_numeric, errors='coerce')
    dddd = final.dropna()
    final = dddd
    final = final[final['direction_y'] != 'buy']

    #################################################################################################

    reg2.loc[:, "volume"] = reg2[['volume_y', 'Bal2', 'Bal1']].min(axis=1)

    reg2.loc[:, 'Vol1'] = reg2['rates_x'] * reg2['volume'] + (
        reg2['rates_x'] * reg2['volume'] * reg2['Com_x'] / 100)
    reg2.loc[:, 'Vol2'] = reg2['volume']
    reg2.loc[:, 'Vol3'] = reg2['volume']
    reg2.loc[:, 'Vol4'] = reg2['rates_y'] * reg2['volume'] - (
        reg2['rates_y'] * reg2['volume'] * reg2['Com_y'] / 100)

    fil_a = reg2[reg2['birga_x'] == 'alfa'].index
    reg2.loc[(fil_a), 'Vol3'] = reg2.loc[(fil_a), 'Vol2'] - (reg2.loc[
        (fil_a), 'Vol2'] * reg2.loc[(fil_a), 'Com_x'] / 100)
    reg2.loc[(fil_a),
             'Vol1'] = reg2.loc[(fil_a), 'rates_x'] * reg2.loc[(fil_a),
                                                               'volume']
    reg2.loc[(fil_a), 'Vol4'] = reg2.loc[(fil_a), 'rates_y'] * reg2.loc[
        (fil_a), 'Vol3'] - (reg2.loc[(fil_a), 'rates_y'] *
                            reg2.loc[(fil_a), 'Vol3'] * reg2['Com_y'] / 100)

    reg2.loc[:, 'profit'] = reg2['Vol4'] - reg2['Vol1']
    reg2.loc[:, 'percent'] = reg2['profit'] / reg2['Vol1'] * 100

    reg2['profit'] = reg2['profit'].apply(pd.to_numeric, errors='coerce')
    reg2['percent'] = reg2['percent'].apply(pd.to_numeric, errors='coerce')

    reg2 = reg2[reg2['direction_y'] != 'buy']
    reg2.to_csv(main_path_data + "\\vilki_all.csv", header=True, index=False)

    #################################################################################################

    def regim_filter():
        fids = pd.DataFrame()
        for k, v in new_regims.items():
            dft = final[(final["birga_x"] == v["birga1"])
                        & (final["birga_y"] == v["birga2"]) &
                        (final["valin_x"] == v["val1"]) &
                        (final["valout_x"] == v["val2"]) &
                        (final["valout_y"] == v["val3"]) &
                        (final["percent"] > float(v["profit"])) &
                        (final["Vol2"] > float(v["order"]))]
            per = (float(v["per"]) / 100)
            dft.loc[:, 'Vol1'] = dft['Vol1'] * per
            dft.loc[:, 'Vol2'] = dft['Vol2'] * per
            dft.loc[:, 'Vol3'] = dft['Vol3'] * per
            dft.loc[:, 'Vol4'] = dft['Vol4'] * per

            dft = dft[(dft["Vol3"] > float(v["order"]))]
            now = dt.datetime.now()
            timerr = now.strftime("%H:%M:%S")
            dft['avtomat'] = v["avtomat"]
            dft['regim'] = k
            dft['timed'] = timerr
            dft = dft.sort_values(by=['Vol2'], ascending=False)
            dft = dft.head(1)
            fids = pd.concat([dft, fids], ignore_index=True, join='outer')
        return fids

    dfs = regim_filter()
    dfs = dfs.reindex(columns=[
        'regim', 'timed', 'birga_x', 'birga_y', 'valin_x', 'valout_x',
        'valout_y', 'rates_x', 'rates_y', 'Vol1', 'Vol2', 'Vol3', 'Vol4',
        'percent', 'avtomat'
    ])
    dfs.columns = [
        'regim', 'timed', 'b1', 'b2', 'val1', 'val2', 'val3', 'kurs1', 'kurs2',
        'Vol1', 'Vol2', 'Vol3', 'Vol4', 'profit', 'Go'
    ]

    dfs['profit'] = dfs['profit'].map('{:,.2f}'.format)
    dfs.index = range(len(dfs))
    dfs = dfs.sort_values(by=['profit'], ascending=False)
    if dfs.shape[0] > 0:
        dfs.to_csv(second_path_data + "\\vilki.csv", header=True, index=False)
        filter1 = dfs[(dfs['Go'] == 'on')]
        if filter1.shape[0] > 0:
            NewOrders.order(filter1.iloc[0]['regim'], filter1.iloc[0]['b1'],
                            filter1.iloc[0]['b2'], filter1.iloc[0]['Vol1'],
                            filter1.iloc[0]['val1'],
                            str(filter1.iloc[0]['kurs1']),
                            filter1.iloc[0]['Vol2'], filter1.iloc[0]['val2'],
                            filter1.iloc[0]['Vol3'], filter1.iloc[0]['val2'],
                            str(filter1.iloc[0]['kurs2']),
                            filter1.iloc[0]['Vol4'], filter1.iloc[0]['val3'])
            Balance.NewBalance()
            time.sleep(1.1)
    else:
        dw2 = {
            'regim': 'пусто',
            'timed': 'пусто',
            'b1': 'пусто',
            'b2': 'пусто',
            'val1': 'пусто',
            'val2': 'пусто',
            'val3': 'пусто',
            'kurs1': 0,
            'kurs2': 0,
            'Vol1': 0,
            'Vol2': 0,
            'Vol3': 0,
            'Vol4': 0,
            'profit': 0,
            'Go': 'пусто',
        }
        df2 = pd.DataFrame(data=dw2, index=[0])
        df2.drop_duplicates(inplace=True)
        df2.to_csv(second_path_data + "\\vilki.csv", header=True, index=False)
    return
Exemplo n.º 2
0
def regim():

    all_vilki2 = pd.read_csv(second_path_data + "\\vilki2_all.csv")
    fids = pd.DataFrame()
    for k, v in regims2.items():
        if v['avtomat'] == 'on':
            dft = vilki_all[(vilki_all["birga_x"] == v["birga1"])
                            & (vilki_all["birga_y"] == v["birga2"]) &
                            (vilki_all["valin_x"] == v["val1"]) &
                            (vilki_all["valout_x"] == v["val2"]) &
                            (vilki_all["Vol3"] > 0) &
                            (vilki_all["volume"] > float(v["order"])) &
                            (vilki_all["valout_y"] == v["val3"])]

            if dft.shape[0] > 0:
                dft.loc[:, 'rates_x'] = dft['rates_x'].map('{:,.9f}'.format)
                dft.loc[:, 'rates_y'] = dft['rates_y'].map('{:,.9f}'.format)
                bir = v["birga1"]
                dft = dft[dft['percent'] == dft['percent'].max()]

                dft.loc[:, 'regim'] = k
                dft.loc[:, 'min_A'] = v["order"]

                if v["val1"] == "BTC":
                    if bir == 'hot':
                        dft.loc[:, 'new_kurs'] = hs_PU2.iloc[0]['rates']
                        dft.loc[:, 'min_kurs'] = hot2.iloc[0]['rates']
                    elif bir == 'live':
                        dft.loc[:, 'new_kurs'] = ls_PU2.iloc[0]['rates']
                        dft.loc[:, 'min_kurs'] = live2.iloc[0]['rates']
                    elif bir == 'alfa':
                        dft.loc[:, 'new_kurs'] = as_PU2.iloc[0]['rates']
                        dft.loc[:, 'min_kurs'] = alfa2.iloc[0]['rates']
                else:
                    if bir == 'hot':
                        dft.loc[:, 'new_kurs'] = hs_PU.iloc[0]['rates']
                        dft.loc[:, 'min_kurs'] = hot.iloc[0]['rates']
                    elif bir == 'live':
                        dft.loc[:, 'new_kurs'] = ls_PU.iloc[0]['rates']
                        dft.loc[:, 'min_kurs'] = live.iloc[0]['rates']
                    elif bir == 'alfa':
                        dft.loc[:, 'new_kurs'] = as_PU.iloc[0]['rates']
                        dft.loc[:, 'min_kurs'] = alfa.iloc[0]['rates']

                tickers_all = [
                    'BTC/USD', 'PZM/USD', 'PZM/USDT', 'ETH/USD', 'ETH/USDT',
                    'PZM/BTC', 'ETH/BTC'
                ]

                parametr1 = "{}/{}".format(v["val1"], v["val2"])
                parametr2 = "{}/{}".format(v["val2"], v["val1"])

                for i in tickers_all:
                    if i == parametr1:
                        para = i
                    elif i == parametr2:
                        para = i

                dft.loc[:, 'My_kurs'] = float(dft.iloc[0]['new_kurs']) + (
                    float(rools2[bir]['amount_precision'][para]) *
                    int(v['per']))
                dft.loc[:, '0_kurs'] = float(dft.iloc[0]['rates_y']) - (
                    float(dft.iloc[0]['rates_y']) * float(v["profit"]) / 100)

                dft['Vol3'] = dft['Vol3'].apply(pd.to_numeric, errors='coerce')
                dft['Vol4'] = dft['Vol4'].apply(pd.to_numeric, errors='coerce')
                dft['My_kurs'] = dft['My_kurs'].apply(pd.to_numeric,
                                                      errors='coerce')

                if bir == 'alfa':
                    dft.loc[:, 'Vol2'] = dft.iloc[0]['Vol3'] + (
                        dft.iloc[0]['Vol3'] * dft.iloc[0]['Com_x'] / 100)
                    dft.loc[:, 'Vol1'] = dft.iloc[0]['Vol2'] * float(
                        dft.iloc[0]['My_kurs'])
                else:
                    dft.loc[:, 'Vol2'] = dft.iloc[0]['Vol3']
                    dft.loc[:, 'Vol1'] = dft.iloc[0]['Vol3'] * dft.iloc[0][
                        'My_kurs'] + (dft.iloc[0]['Vol3'] *
                                      dft.iloc[0]['My_kurs'] *
                                      dft.iloc[0]['Com_x'] / 100)

                dft.loc[:, 'prof'] = dft['Vol4'] - dft['Vol1']

                dft.loc[:, 'per'] = dft['prof'] / dft['Vol1'] * 100
                dft.loc[:, 'New_per'] = float(v["profit"])
                dft.drop(['index'], axis=1, inplace=True)

                df_vilki = vilki2[vilki2["regim"] == int(k)]

                if df_vilki.shape[0] > 0:
                    my_order = int(df_vilki.iloc[0]['order_id'])
                    my_dict = finished_orders[df_vilki.iloc[0]['birga_x']]
                    if str(my_order) in my_dict:
                        if my_dict[str(my_order)] >= float(
                                df_vilki.iloc[0]['min_A']):
                            check_vol = float(
                                df_vilki.iloc[0]['Vol2']) - float(
                                    my_dict[str(my_order)])
                            if check_vol <= 0:
                                birga = df_vilki.iloc[0]['birga_y']
                                val3 = df_vilki.iloc[0]['valin_y']
                                val4 = df_vilki.iloc[0]['valout_y']
                                rate2 = str(df_vilki.iloc[0]['rates_y'])
                                val3_vol = df_vilki.iloc[0]['Vol3']

                                if birga == 'alfa':
                                    reponse = Reg2_Orders.alfa(
                                        val3, val4, rate2, val3_vol)
                                elif birga == 'live':
                                    reponse = Reg2_Orders.live(
                                        val3, val4, rate2, val3_vol)
                                elif birga == 'hot':
                                    reponse = Reg2_Orders.hot(
                                        val3, val4, rate2, val3_vol)
                                else:
                                    reponse = "No such BIRGA"

                                now = dt.datetime.now()
                                timer2 = now.strftime("%Y-%m-%d %H:%M:%S")
                                profit = (df_vilki.iloc[0]['Vol4'] -
                                          df_vilki.iloc[0]['Vol1']
                                          ) / df_vilki.iloc[0]['Vol1'] * 100

                                dw2 = {
                                    'regim': df_vilki.iloc[0]['regim'],
                                    'timed': [timer2],
                                    'b1': [df_vilki.iloc[0]['birga_x']],
                                    'b2': [df_vilki.iloc[0]['birga_y']],
                                    'val1': [df_vilki.iloc[0]['valin_x']],
                                    'val2': [df_vilki.iloc[0]['valout_x']],
                                    'val3': [df_vilki.iloc[0]['valout_y']],
                                    'kurs1': [df_vilki.iloc[0]['rates_x']],
                                    'kurs2': [df_vilki.iloc[0]['rates_y']],
                                    'Vol1': [df_vilki.iloc[0]['Vol1']],
                                    'Vol2': [df_vilki.iloc[0]['Vol2']],
                                    'Vol3': [df_vilki.iloc[0]['Vol3']],
                                    'Vol4': [df_vilki.iloc[0]['Vol4']],
                                    'profit': [profit],
                                    'rep1': [reponse],
                                    'rep2': [my_order],
                                }
                                df2 = pd.DataFrame(data=dw2, index=[0])
                                df2.drop_duplicates(inplace=True)
                                all_vilki2 = pd.concat([dft, all_vilki2],
                                                       ignore_index=True,
                                                       join='outer')
                                nl = '\n'
                                bot_sendtext(
                                    f" ЕСТЬ ВИЛКА: {nl} РЕЖИМ : {df_vilki.iloc[0]['regim']} {nl} {df_vilki.iloc[0]['birga_x']} / {df_vilki.iloc[0]['birga_y']} {nl} "
                                    f"{reponse} / {my_order} {nl} {df_vilki.iloc[0]['valin_x']} -> {df_vilki.iloc[0]['valout_x']} -> {df_vilki.iloc[0]['valout_y']} {nl} "
                                    f"PROFIT: {profit} {nl} ")

                                vilki2.drop(
                                    vilki2.index[vilki2["regim"] == int(k)],
                                    inplace=True)

                                ###############  delete from finished json  #############################

                                a_file = open(
                                    main_path_data + "\\finished_orders.json",
                                    "r")
                                json_object = json.load(a_file)
                                a_file.close()

                                del json_object[df_vilki.iloc[0]['birga_x']][
                                    str(my_order)]

                                a_file = open(
                                    main_path_data + "\\finished_orders.json",
                                    "w")
                                json.dump(json_object, a_file)
                                a_file.close()
                                Balance.NewBalance()
                            elif check_vol > 0 and check_vol < float(
                                    df_vilki.iloc[0]['min_A']):
                                birga = df_vilki.iloc[0]['birga_x']
                                val3 = df_vilki.iloc[0]['valin_y']
                                val4 = df_vilki.iloc[0]['valout_y']
                                rate2 = df_vilki.iloc[0]['rates_y']
                                birga2 = df_vilki.iloc[0]['birga_y']
                                nl = '\n'
                                if birga == 'alfa':
                                    val1_vol = (my_dict[str(my_order)] *
                                                df_vilki.iloc[0]['My_kurs'])
                                    val2_vol = my_dict[str(my_order)]
                                    val3_vol = my_dict[str(my_order)] - (
                                        my_dict[str(my_order)] *
                                        df_vilki.iloc[0]['Com_x'] / 100)
                                    val4_vol = (
                                        val3_vol * df_vilki.iloc[0]['rates_y']
                                    ) - (val3_vol * df_vilki.iloc[0]['rates_y']
                                         * df_vilki.iloc[0]['Com_y'] / 100)
                                else:
                                    val1_vol = (
                                        my_dict[str(my_order)] *
                                        df_vilki.iloc[0]['My_kurs']) + (
                                            my_dict[str(my_order)] *
                                            df_vilki.iloc[0]['rates_x'] *
                                            df_vilki.iloc[0]['Com_x'] / 100)
                                    val2_vol = my_dict[str(my_order)]
                                    val3_vol = my_dict[str(my_order)]
                                    val4_vol = (
                                        val3_vol * df_vilki.iloc[0]['rates_y']
                                    ) - (val3_vol * df_vilki.iloc[0]['rates_y']
                                         * df_vilki.iloc[0]['Com_y'] / 100)

                                if birga2 == 'alfa':
                                    reponse = Reg2_Orders.alfa(
                                        val3, val4, str(rate2), val3_vol)
                                elif birga2 == 'live':
                                    reponse = Reg2_Orders.live(
                                        val3, val4, str(rate2), val3_vol)
                                elif birga2 == 'hot':
                                    reponse = Reg2_Orders.hot(
                                        val3, val4, str(rate2), val3_vol)
                                else:
                                    reponse = "No such BIRGA"

                                if birga == 'alfa':
                                    reponse2 = Reg2_Orders.alfa_cancel(
                                        str(my_order))
                                elif birga == 'live':
                                    reponse2 = Reg2_Orders.live_cancel(
                                        df_vilki.iloc[0]['valin_x'],
                                        df_vilki.iloc[0]['valout_x'],
                                        str(my_order))
                                elif birga == 'hot':
                                    reponse2 = Reg2_Orders.hot_cancel(
                                        df_vilki.iloc[0]['valin_x'],
                                        df_vilki.iloc[0]['valout_x'],
                                        str(my_order))
                                else:
                                    reponse2 = "No such BIRGA"
                                now = dt.datetime.now()
                                timer2 = now.strftime("%Y-%m-%d %H:%M:%S")

                                profit = (val4_vol - val1_vol) / val1_vol * 100
                                dw2 = {
                                    'regim': df_vilki.iloc[0]['regim'],
                                    'timed': [timer2],
                                    'b1': [df_vilki.iloc[0]['birga_x']],
                                    'b2': [df_vilki.iloc[0]['birga_y']],
                                    'val1': [df_vilki.iloc[0]['valin_x']],
                                    'val2': [df_vilki.iloc[0]['valout_x']],
                                    'val3': [df_vilki.iloc[0]['valout_y']],
                                    'kurs1': [df_vilki.iloc[0]['My_kurs']],
                                    'kurs2': [df_vilki.iloc[0]['rates_y']],
                                    'Vol1': [val1_vol],
                                    'Vol2': [val2_vol],
                                    'Vol3': [val3_vol],
                                    'Vol4': [val4_vol],
                                    'profit': [profit],
                                    'rep1': [reponse],
                                    'rep2': [my_order],
                                }
                                df2 = pd.DataFrame(data=dw2, index=[0])
                                df2.drop_duplicates(inplace=True)
                                all_vilki2 = pd.concat([dft, all_vilki2],
                                                       ignore_index=True,
                                                       join='outer')

                                bot_sendtext(
                                    f" ЕСТЬ ВИЛКА: {nl} РЕЖИМ : {df_vilki.iloc[0]['regim']} {nl} {df_vilki.iloc[0]['birga_x']} / {df_vilki.iloc[0]['birga_y']} {nl} "
                                    f"{reponse} / {my_order} {nl} {df_vilki.iloc[0]['valin_x']} -> {df_vilki.iloc[0]['valout_x']} -> {df_vilki.iloc[0]['valout_y']} {nl} "
                                    f"{df_vilki.iloc[0]['birga_x']} / {df_vilki.iloc[0]['rates_y']} {nl} "
                                    f"{df_vilki.iloc[0]['Vol2']} / {df_vilki.iloc[0]['Vol3']} {nl} "
                                    f"PROFIT: {profit} {nl} ")

                                vilki2.drop(
                                    vilki2.index[vilki2["regim"] == int(k)],
                                    inplace=True)

                                ###############  delete from finished json  #############################

                                a_file32 = open(
                                    main_path_data + "\\finished_orders.json",
                                    "r")
                                json_object = json.load(a_file32)
                                a_file32.close()

                                del json_object[df_vilki.iloc[0]['birga_x']][
                                    str(my_order)]

                                a_file23 = open(
                                    main_path_data + "\\finished_orders.json",
                                    "w")
                                json.dump(json_object, a_file23)
                                a_file23.close()
                                Balance.NewBalance()
                        else:
                            del my_dict[str(my_order)]
                            f33 = open(
                                main_path_data + "\\finished_orders.json", "w")
                            json.dump(my_dict, f33)
                            f33.close()
                    else:
                        print("######  dft  ######", '\n', dft, '\n')
                        adf = dft[
                            (dft['per'] >= dft['New_per']) &
                            # (float(dft['My_kurs']) <= float(df_vilki.iloc[0]['My_kurs'])) &
                            (float(dft['rates_y']) >= float(df_vilki.iloc[0]
                                                            ['rates_y'])) &
                            (dft['Vol2'] >= float(df_vilki.iloc[0]['Vol2']))]

                        # print( "PERC :", dft.iloc[0]['per'], "___###___", "PERC NEW :",dft.iloc[0]['New_per'])
                        # print("My_kurs :", dft.iloc[0]['My_kurs'], "___###___", "My_kurs OLD :", df_vilki.iloc[0]['My_kurs'])
                        # print("rates_y :", dft.iloc[0]['rates_y'], "___###___", "rates_y OLD :", df_vilki.iloc[0]['rates_y'])
                        # print( "Vol2 :", dft.iloc[0]['Vol2'], "___###___", "Vol2 OLD :",df_vilki.iloc[0]['Vol2'])

                        print('\n', "######  adf  ######", '\n', adf, '\n')
                        if adf.shape[0] > 0:
                            pass
                        else:
                            bir = df_vilki.iloc[0]['birga_x']
                            if bir == 'alfa':
                                reponse2 = Reg2_Orders.alfa_cancel(
                                    df_vilki.iloc[0]['order_id'])
                            elif bir == 'live':
                                reponse2 = Reg2_Orders.live_cancel(
                                    df_vilki.iloc[0]['valin_x'],
                                    df_vilki.iloc[0]['valout_x'],
                                    df_vilki.iloc[0]['order_id'])
                            elif bir == 'hot':
                                reponse2 = Reg2_Orders.hot_cancel(
                                    df_vilki.iloc[0]['valin_x'],
                                    df_vilki.iloc[0]['valout_x'],
                                    df_vilki.iloc[0]['order_id'])
                            else:
                                reponse2 = "No such BIRGA"
                            vilki2.drop(
                                vilki2.index[vilki2["regim"] == int(k)],
                                inplace=True)

                            ###############  delete from finished json  #############################

                            a_file = open(
                                main_path_data + "\\finished_orders.json", "r")
                            json_object = json.load(a_file)
                            a_file.close()
                            # print("######",str(int(df_vilki.iloc[0]['order_id'])))

                            if str(int(df_vilki.iloc[0]
                                       ['order_id'])) in json_object[bir]:
                                del json_object[bir][str(
                                    int(df_vilki.iloc[0]['order_id']))]

                            a_file = open(
                                main_path_data + "\\finished_orders.json", "w")
                            json.dump(json_object, a_file)
                            a_file.close()

                else:
                    # print("######  dft  ######", '\n', dft, '\n')
                    dft = dft[(dft["per"] > float(dft.iloc[0]["New_per"]))
                              & (dft["Vol2"] > float(dft.iloc[0]["min_A"])) &
                              (dft['My_kurs'] < float(
                                  dft.iloc[0]["min_kurs"]))]

                    # print(dft)
                    if dft.shape[0] > 0:
                        val1 = dft.iloc[0]['valin_x']
                        val2 = dft.iloc[0]['valout_x']
                        rate1 = str(dft.iloc[0]['My_kurs'])
                        val2_vol = dft.iloc[0]['Vol2']

                        if bir == 'alfa':
                            reponse = Reg2_Orders.alfa(val1, val2, rate1,
                                                       val2_vol)
                        elif bir == 'live':
                            reponse = Reg2_Orders.live(val1, val2, rate1,
                                                       val2_vol)
                        elif bir == 'hot':
                            reponse = Reg2_Orders.hot(val1, val2, rate1,
                                                      val2_vol)
                        else:
                            reponse = "No such BIRGA"
                            pass
                        dft.loc[:, 'order_id'] = reponse
                        vilki2 = pd.concat([dft, vilki2],
                                           ignore_index=True,
                                           join='outer')

                fids = pd.concat([dft, fids], ignore_index=True, join='outer')

    vilki2.to_csv(second_path_data + "\\vilki2.csv", header=True, index=False)
    all_vilki2.to_csv(second_path_data + "\\vilki2_all.csv",
                      header=True,
                      index=False)