
from base_class import BaseVariableFunction
from base_class import *
baseclass = BaseVariableFunction(__file__)
baseclass.makedirpath(baseclass.dalao_profit_st_fm_path)
baseclass.makedirpath(baseclass.dalao_ana_fm_path)


baseclass.makedirpath(baseclass.dalao_total_ana_fm_path)
baseclass.open_base_library()
decimal.getcontext().prec = 100
old_print = print


def timestamped_print(*args, **kwargs):
    old_print(datetime.datetime.utcnow().replace(
        microsecond=0), *args, **kwargs)


print = timestamped_print
print('\n'*5)
print(f"{'{:<6}'.format('ENTER')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")

onedalao_ana_columns = ['TokenFirstTime', 'swap_tokenaddress', "issellfir", 'buy_counts', 'sell_counts',
                        'outtoken_per', 'cost_main', 'earn_main', 'earn_percent' ,
                        'diffdays','fir_cost_main','fir_earn_percent' , 'fir_noadd_earn_percent']

    
onetxhash_onerow_ana_cols= [
"sign","swap_tokenaddress","dexurl","platform","datetime",
"dalaofirsttimestamp","diffdays",
"fir_cost_main","fir_earn_percent","issellfir",
"fir_noadd_earn_percent","token_price", "buy_sell_diftime",

"swap_type",
"outtoken_per",
"buy_counts","sell_counts",
"timestamp","TokenFirstTime",
"swap_eth_amount","swap_token_amount",
"cost_main","earn_main","earn_percent",
"intoken_amount","outtoken_amount",
    ]
    

TotalAnalysis_columns = [
    "add",
    # "whichcontract",
    "url",
    "beizhu",

    "03d_cost",
    "03d_earn",
    "03d_earnper",
    "03d_difcost",
    "03d_difearn",
    "03d_difper",
    "03d_costmedian",
    "03d_costmean",
    "03d_cost_noaddouttoken",
    "03d_earn_noaddouttoken",
    "03d_earnper_noaddouttoken",
    # "03d_difcost_noaddouttoken",
    # "03d_difearn_noaddouttoken",
    # "03d_difper_noaddouttoken",
    # "03d_costmedian_noaddouttoken",
    # "03d_costmean_noaddouttoken",
    "03d_mine_fir_earnper",
    "03d_mine_fir_earnper_dropmax",
    "03d_mine_fir_earnper_droptwomax",
    "03d_mine_noadd_fir_earnper" , 
    "03d_mine_noadd_fir_earnper_dropmax" , 
    "03d_mine_noadd_fir_earnper_droptwomax" ,

    "03d_trans",


    "07d_cost",
    "07d_earn",
    "07d_earnper",
    "07d_difcost",
    "07d_difearn",
    "07d_difper",
    "07d_costmedian",
    "07d_costmean",
    "07d_cost_noaddouttoken",
    "07d_earn_noaddouttoken",
    "07d_earnper_noaddouttoken",
    # "07d_difcost_noaddouttoken",
    # "07d_difearn_noaddouttoken",
    # "07d_difper_noaddouttoken",
    # "07d_costmedian_noaddouttoken",
    # "07d_costmean_noaddouttoken",
    "07d_mine_fir_earnper",
    "07d_mine_fir_earnper_dropmax",
    "07d_mine_fir_earnper_droptwomax",
    "07d_mine_noadd_fir_earnper" , 
    "07d_mine_noadd_fir_earnper_dropmax" , 
    "07d_mine_noadd_fir_earnper_droptwomax" ,
    "07d_trans",


    # "11d_cost",
    # "11d_earn",
    # "11d_earnper",
    # "11d_difcost",
    # "11d_difearn",
    # "11d_difper",
    # "11d_costmedian",
    # "11d_costmean",
    # "11d_cost_noaddouttoken",
    # "11d_earn_noaddouttoken",
    # "11d_earnper_noaddouttoken",
    # # "11d_difcost_noaddouttoken",
    # # "11d_difearn_noaddouttoken",
    # # "11d_difper_noaddouttoken",
    # # "11d_costmedian_noaddouttoken",
    # # "11d_costmean_noaddouttoken",
    # "11d_mine_fir_earnper",
    # "11d_mine_fir_earnper_dropmax",
    # "11d_mine_fir_earnper_droptwomax",
    # "11d_mine_noadd_fir_earnper" , 
    # "11d_mine_noadd_fir_earnper_dropmax" , 
    # "11d_mine_noadd_fir_earnper_droptwomax" ,
    # "11d_trans",


    "15d_cost",
    "15d_earn",
    "15d_earnper",
    "15d_difcost",
    "15d_difearn",
    "15d_difper",
    "15d_costmedian",
    "15d_costmean",
    "15d_cost_noaddouttoken",
    "15d_earn_noaddouttoken",
    "15d_earnper_noaddouttoken",
    # "15d_difcost_noaddouttoken",
    # "15d_difearn_noaddouttoken",
    # "15d_difper_noaddouttoken",
    # "15d_costmedian_noaddouttoken",
    # "15d_costmean_noaddouttoken",
    "15d_mine_fir_earnper",
    "15d_mine_fir_earnper_dropmax",
    "15d_mine_fir_earnper_droptwomax",
    "15d_mine_noadd_fir_earnper" , 
    "15d_mine_noadd_fir_earnper_dropmax" , 
    "15d_mine_noadd_fir_earnper_droptwomax" ,
    "15d_trans",

 
    "30d_cost",
    "30d_earn",
    "30d_earnper",
    "30d_difcost",
    "30d_difearn",
    "30d_difper",
    "30d_costmedian",
    "30d_costmean",
    "30d_cost_noaddouttoken",
    "30d_earn_noaddouttoken",
    "30d_earnper_noaddouttoken",
    # "30d_difcost_noaddouttoken",
    # "30d_difearn_noaddouttoken",
    # "30d_difper_noaddouttoken",
    # "30d_costmedian_noaddouttoken",
    # "30d_costmean_noaddouttoken",
    "30d_mine_fir_earnper",
    "30d_mine_fir_earnper_dropmax",
    "30d_mine_fir_earnper_droptwomax",
    "30d_mine_noadd_fir_earnper" , 
    "30d_mine_noadd_fir_earnper_dropmax" , 
    "30d_mine_noadd_fir_earnper_droptwomax" ,
    "30d_trans",

    "30dearn_dif",
   "30d_mine_fir_earnper_dif",
]



earn_kuisun_columns=[
      "add",
       "url",
    "beizhu",

    "03d_bigbig_earn_counts"  , "03d_big_earn_counts"   , "03d_nor_earn_counts"  ,
    "03d_nor_kuisun_counts"  , "03d_big_kuisun_counts"   , "03d_bigbig_kuisun_counts"  ,
    "03d_bigbig_earn_per"  , "03d_big_earn_per"   , "03d_nor_earn_per"  ,
    "03d_nor_kuisun_per"  , "03d_big_kuisun_per"   , "03d_bigbig_kuisun_per"  ,
    "03d_total_counts",

    "07d_bigbig_earn_counts"  , "07d_big_earn_counts"   , "07d_nor_earn_counts"  ,
    "07d_nor_kuisun_counts"  , "07d_big_kuisun_counts"   , "07d_bigbig_kuisun_counts"  ,
    "07d_bigbig_earn_per"  , "07d_big_earn_per"   , "07d_nor_earn_per"  ,
    "07d_nor_kuisun_per"  , "07d_big_kuisun_per"   , "07d_bigbig_kuisun_per"  ,
    "07d_total_counts",

    # "11d_bigbig_earn_counts"  , "11d_big_earn_counts"   , "11d_nor_earn_counts"  ,
    # "11d_nor_kuisun_counts"  , "11d_big_kuisun_counts"   , "11d_bigbig_kuisun_counts"  ,
    # "11d_bigbig_earn_per"  , "11d_big_earn_per"   , "11d_nor_earn_per"  ,
    # "11d_nor_kuisun_per"  , "11d_big_kuisun_per"   , "11d_bigbig_kuisun_per"  ,
    # "11d_total_counts",

    "15d_bigbig_earn_counts"  , "15d_big_earn_counts"   , "15d_nor_earn_counts"  ,
    "15d_nor_kuisun_counts"  , "15d_big_kuisun_counts"   , "15d_bigbig_kuisun_counts"  ,
    "15d_bigbig_earn_per"  , "15d_big_earn_per"   , "15d_nor_earn_per"  ,
    "15d_nor_kuisun_per"  , "15d_big_kuisun_per"   , "15d_bigbig_kuisun_per"  ,
    "15d_total_counts",



    "30d_bigbig_earn_counts"  , "30d_big_earn_counts"   , "30d_nor_earn_counts"  ,
    "30d_nor_kuisun_counts"  , "30d_big_kuisun_counts"   , "30d_bigbig_kuisun_counts"  ,
    "30d_bigbig_earn_per"  , "30d_big_earn_per"   , "30d_nor_earn_per"  ,
    "30d_nor_kuisun_per"  , "30d_big_kuisun_per"   , "30d_bigbig_kuisun_per"  ,
    "30d_total_counts",

]

def get_txhash_tokenswap_amount(df):
    def get_txhash_cost(gdf):
        token_amount_list = gdf['swap_token_amount'].to_list()
        arr_token_amount = [(decimal.Decimal(
            token_amount)) for token_amount in token_amount_list]
        token_amount = sum(arr_token_amount)
        token_amount_str = '{0:.4f}'.format(token_amount)
        gdf[['swap_token_amount']] = [token_amount_str]
        # gdf['swap_token_amount'] = token_amount_str
        return gdf

    df = df.groupby(["sign"], group_keys=False).apply(
        lambda gdf:  get_txhash_cost(gdf))
    df = df.reset_index(drop=True)
    return df


def get_tokenswap_amount(df):
    def get_cost(gdf):
        arr_token_amount = gdf['swap_token_amount'].to_list()
        isfirstsell = False
        while len(arr_token_amount) > 0:
            if (decimal.Decimal(arr_token_amount[0]) < 0):
                arr_token_amount.pop(0)
                isfirstsell = True
            else:
                break
        if len(arr_token_amount) == 0:
            return gdf
        arr_out_token_amount = [abs(decimal.Decimal(
            token_amount)) for token_amount in arr_token_amount if decimal.Decimal(token_amount) < 0]
        arr_in_token_amount = [decimal.Decimal(
            token_amount) for token_amount in arr_token_amount if decimal.Decimal(token_amount) > 0]
        buy_counts = len(arr_in_token_amount)
        sell_counts = len(arr_out_token_amount)

        out_token_amount = sum(arr_out_token_amount)
        in_token_amount = sum(arr_in_token_amount)

        out_token_amount_str = '{0:.2f}'.format(out_token_amount)
        in_token_amount_str = '{0:.2f}'.format(in_token_amount)
        if isfirstsell:
            outtoken_per = "1.01"
        else:
            outtoken_per = '{0:.2f}'.format(
                out_token_amount/in_token_amount) if in_token_amount != 0 else '-10'
        gdf[['buy_counts', 'sell_counts', 'intoken_amount', 'outtoken_amount', 'outtoken_per']] = [buy_counts, sell_counts,
                                                                                                   in_token_amount_str, out_token_amount_str, outtoken_per]
        return gdf
    df[['buy_counts', 'sell_counts', 'intoken_amount',
        'outtoken_amount', 'outtoken_per']] = [0, 0, '0', '0', '0']
    # 如果全是sell token 那么 在get_cost（）将会在中途返回gdf 不会赋值 如上变量全为0
    df = df.groupby(["swap_tokenaddress"], group_keys=False).apply(
        lambda gdf:  get_cost(gdf))
    df = df.reset_index(drop=True)
    return df


def get_sol_profit(df):
    # 計算利潤
    df['cost_main'] = 0
    df['earn_main'] = 0
    df['earn_percent'] = -10
    df['fir_cost_main'] = 0
    df['fir_earn_percent']=-10
    df["issellfir"] = 0
    df["fir_noadd_earn_percent"] = -10
    df["token_price"]=-10
    df["buy_sell_diftime"]=-1
   
    df = df.astype({'swap_eth_amount': float})
    df = df.astype({'swap_token_amount': float})
    df = df.astype({'outtoken_per': float})
    df = df.astype({'timestamp': int})

     

 
    df["token_price"] = np.where(
        df['swap_token_amount'] != 0,
        -df['swap_eth_amount'] / df['swap_token_amount'],
        -10,
    )
 

    def get_one_sol_profit(gdf):
        issellfir = False
        arr_eth_amount = gdf['swap_eth_amount'].to_list()
        arr_token_amount = gdf['swap_token_amount'].to_list()
        arr_timestamp = gdf["timestamp"].to_list()
        
        while len(arr_eth_amount) > 0:
            # 如果 arr_eth_amount[0]>0 则此交易为卖出 pass

            if (arr_eth_amount[0] >= 0):
                gdf["issellfir"] = 1
                arr_eth_amount.pop(0)
                arr_token_amount.pop(0)
                arr_timestamp.pop(0)
                continue
            else:
                break
        if len(arr_eth_amount) == 0:
            return gdf
        number_cost_main = sum(
            [abs(eth_amount) for eth_amount in arr_eth_amount if eth_amount < 0])
        number_earn_main = sum(arr_eth_amount)

        number_earn_percent = number_earn_main / \
            number_cost_main if number_cost_main != 0 else -10
        gdf["cost_main"] = number_cost_main
        gdf["earn_main"] = number_earn_main
        gdf["earn_percent"] = number_earn_percent

        arr_firswap_token_amount = arr_token_amount.copy()
        arr_firswap_eth_amount = arr_eth_amount.copy()

        # swap_tokenaddress
        small_sol_counts = 0
        # 获取第一笔cost_eth
         # 如果 arr_eth_amount[0]>0 则此交易为卖出 pass
         # 如果 0>arr_eth_amount[0]>-0.04 此交易金额较小 pass
        while len(arr_firswap_eth_amount) > 0:
            if arr_firswap_eth_amount[0]>=0:
                arr_firswap_eth_amount.pop(0)
                arr_firswap_token_amount.pop(0)
                arr_timestamp.pop(0)
                continue
            elif arr_firswap_eth_amount[0]<0 and arr_firswap_eth_amount[0]>-0.04:
                arr_firswap_eth_amount.pop(0)
                arr_firswap_token_amount.pop(0)
                arr_timestamp.pop(0)
                small_sol_counts+=1
                if small_sol_counts==2:
                    break
                continue
            else :
                break
        if small_sol_counts==2:
            return gdf
        if len(arr_firswap_eth_amount) == 0:
            return gdf  

        fir_swap_tokenamount = arr_firswap_token_amount[0]
        fir_swap_costmain = abs(arr_firswap_eth_amount[0])
        fir_swap_earntmain = -fir_swap_costmain
        fir_buy_timestamp =int(arr_timestamp[0])
        fir_sell_timestamp = 0

        while len(arr_firswap_eth_amount) > 0:
            if arr_firswap_eth_amount[0]<=0:
                arr_firswap_eth_amount.pop(0)
                arr_firswap_token_amount.pop(0)
                arr_timestamp.pop(0)
                continue
            # 现在 swap_token 为负 ， eth为正 代表 sell token
            cur_swap_tokenamount = abs(arr_firswap_token_amount[0])
            cur_swap_eth = arr_firswap_eth_amount[0]
            fir_sell_timestamp = int(arr_timestamp[0])
            arr_firswap_eth_amount.pop(0)
            arr_firswap_token_amount.pop(0)
            arr_timestamp.pop(0)
            if fir_swap_tokenamount>=cur_swap_tokenamount:
                fir_swap_earntmain+=cur_swap_eth
                fir_swap_tokenamount-=cur_swap_tokenamount
            else:
                fir_swap_earntmain = fir_swap_earntmain+  fir_swap_tokenamount/cur_swap_tokenamount * cur_swap_eth
                fir_swap_tokenamount=0
            if fir_swap_tokenamount==0:
                break
        gdf['fir_cost_main'] = fir_swap_costmain
        gdf["fir_earn_percent"] = fir_swap_earntmain / fir_swap_costmain  if fir_swap_costmain != 0 else -10
        gdf["fir_noadd_earn_percent"] = fir_swap_earntmain / fir_swap_costmain  if fir_swap_costmain != 0 else -10
        if issellfir==1 or gdf["outtoken_per"].tolist()[0]>1:
            gdf["fir_noadd_earn_percent"] = -10
        gdf["buy_sell_diftime"] = fir_sell_timestamp - fir_buy_timestamp
        return gdf

    df = df.groupby(["swap_tokenaddress"], group_keys=False).apply(
        lambda gdf:  get_one_sol_profit(gdf))

    return df




def analysis_lastdays( df, now_unix_time, intervaldays=30):
    if len(df) == 0:
        return 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0,0
    # need consider df may null if use iloc
    lastdf = df[df["TokenFirstTime"] >=
                now_unix_time - 3600*24*intervaldays]
    # 去除那些earnper为-10的
    lastdf = lastdf[lastdf['cost_main'] != 0]
    # 去除 cost_main 过小的 <0.04  sol 理论上 同时fir_cost_main!=0
    lastdf = lastdf[lastdf['cost_main'] >= 0.04]
    lastdf = lastdf[lastdf['fir_cost_main'] != 0]
    lastdf = lastdf[lastdf['issellfir'] ==0]


    lastdf = lastdf.reset_index(drop=True)
    if len(lastdf) == 0:
        return 0, 0, 0, 0, 0, 0, 0, 0, 0,0,0,0
    last_mine_fir_earnper =  lastdf['fir_earn_percent'].sum()
    last_mine_fir_earnper_dropmax = last_mine_fir_earnper- lastdf['fir_earn_percent'].max()
    last_mine_fir_earnper_droptwomax = last_mine_fir_earnper - sum( lastdf['fir_earn_percent'].nlargest(2).tolist())

    last_cost_sum = lastdf['cost_main'].sum()
    last_earn_sum = lastdf['earn_main'].sum()
    last_cost_median = lastdf['cost_main'].median()
    last_cost_mean = lastdf['cost_main'].mean()
    last_earnper = last_earn_sum / last_cost_sum if last_cost_sum != 0 else -10
    last_trans_amount = len(lastdf)
    lastdf['earn_percent'] = np.where(
        lastdf['cost_main'] != 0,
        lastdf['earn_main'] / lastdf['cost_main'],
        -10,
    )
    earnmain_max = lastdf['earn_main'].max()
    last_earn_difmax_sum = last_earn_sum - earnmain_max
    last_cost_difmax_sum = last_cost_sum - \
        lastdf[lastdf['earn_main'] == earnmain_max]['cost_main'].to_list()[0]
    last_dif_earnper = (
        last_earn_difmax_sum / last_cost_difmax_sum if last_cost_difmax_sum != 0 else -10
    )
    return (
        last_cost_sum,
        last_earn_sum,
        last_earnper,
        last_cost_difmax_sum,
        last_earn_difmax_sum,
        last_dif_earnper,
        last_cost_median,
        last_cost_mean,
        # last_earncount_per,
        last_trans_amount,
        last_mine_fir_earnper,
        last_mine_fir_earnper_dropmax,
        last_mine_fir_earnper_droptwomax,
    )

def analysis_lastdays_noaddouttoken( df, now_unix_time, intervaldays=30):
    if len(df) == 0:
        return 0, 0, 0, 0, 0,  0, 0, 0, 0,0,0,0
    # need consider df may null if use iloc
    lastdf = df[df["TokenFirstTime"] >=
                now_unix_time - 3600*24*intervaldays]
    # 去除那些earnper为-10的
    lastdf = lastdf[lastdf['cost_main'] != 0]
    # 去除 cost_main 过小的 <0.04  sol 理论上 同时fir_cost_main!=0
    lastdf = lastdf[lastdf['cost_main'] >= 0.04] 
    lastdf = lastdf[lastdf['fir_cost_main'] != 0]
    # fir_noadd_earn_percent
    # 去除 第一笔交易是sell
    lastdf = lastdf[lastdf['fir_noadd_earn_percent'] !=-10]
    lastdf = lastdf[lastdf['issellfir'] ==0]
    lastdf = lastdf.reset_index(drop=True)
    if len(lastdf) == 0:
        return 0, 0, 0, 0, 0,  0, 0, 0, 0,0,0,0
    
    last_mine_noadd_fir_earnper =  lastdf['fir_noadd_earn_percent'].sum()
    last_mine_noadd_fir_earnper_dropmax = last_mine_noadd_fir_earnper- lastdf['fir_noadd_earn_percent'].max()
    last_mine_noadd_fir_earnper_droptwomax = last_mine_noadd_fir_earnper - sum( lastdf['fir_noadd_earn_percent'].nlargest(2).tolist())
    last_cost_sum = lastdf['cost_main'].sum()
    last_earn_sum = lastdf['earn_main'].sum()
    # last_earn_sum = lastdf["earn_main_noaddouttoken"].sum()
    last_cost_median = lastdf['cost_main'].median()
    last_cost_mean = lastdf['cost_main'].mean()
    last_earnper = last_earn_sum / last_cost_sum if last_cost_sum != 0 else -10
    last_trans_amount = len(lastdf)
    lastdf['earn_percent'] = np.where(
        lastdf['cost_main'] != 0,
        lastdf["earn_main"] / lastdf['cost_main'],
        -10,
    )

    earnmain_max = lastdf["earn_main"].max()
    last_earn_difmax_sum = last_earn_sum - earnmain_max
    last_cost_difmax_sum = last_cost_sum - \
        lastdf[lastdf['earn_main'] == earnmain_max]['cost_main'].to_list()[
            0]
    last_dif_earnper = (
        last_earn_difmax_sum / last_cost_difmax_sum if last_cost_difmax_sum != 0 else -10
    )
    return (
        last_cost_sum,
        last_earn_sum,
        last_earnper,
        last_cost_difmax_sum,
        last_earn_difmax_sum,
        last_dif_earnper,
        last_cost_median,
        last_cost_mean,
        # last_earncount_per,
        last_trans_amount,
        last_mine_noadd_fir_earnper , 
        last_mine_noadd_fir_earnper_dropmax ,
        last_mine_noadd_fir_earnper_droptwomax
    )

def analysis_lastdays_earn_kuisun_counts(df ,now_unix_time,intervaldays ):
    if len(df) == 0:
        return 0, 0, 0, 0, 0, 0, 0 ,0,0,0,0,0,0
    # need consider df may null if use iloc
    lastdf = df[df["TokenFirstTime"] >=
                now_unix_time - 3600*24*intervaldays]
    # 去除那些earnper为-10的
    lastdf = lastdf[lastdf['cost_main'] != 0]
    # 去除 cost_main 过小的 <0.04  sol 理论上 同时fir_cost_main!=0
    lastdf = lastdf[lastdf['cost_main'] >= 0.04] 
    lastdf = lastdf[lastdf['fir_cost_main'] != 0]
    # fir_noadd_earn_percent
    # 去除 第一笔交易是sell
    lastdf = lastdf[lastdf['fir_noadd_earn_percent'] !=-10]
    lastdf = lastdf[lastdf['issellfir'] ==0]
    lastdf = lastdf.reset_index(drop=True)
    if len(lastdf) == 0:
        return 0, 0, 0, 0, 0, 0, 0 ,0,0,0,0,0,0
    

    last_bigbig_earn_counts = len( lastdf[lastdf['fir_noadd_earn_percent']>=1])
    last_big_earn_counts = len( lastdf[(lastdf['fir_noadd_earn_percent']>=0.5 )& (lastdf['fir_noadd_earn_percent']<1 ) ])
    last_nor_earn_counts = len( lastdf[(lastdf['fir_noadd_earn_percent']>=0.05 )& (lastdf['fir_noadd_earn_percent']<0.5 ) ])

    last_nor_kuisun_counts = len( lastdf[(lastdf['fir_noadd_earn_percent']>=-0.2 )& (lastdf['fir_noadd_earn_percent']<0.05 ) ])
    last_big_kuisun_counts = len( lastdf[(lastdf['fir_noadd_earn_percent']>=-0.5 )& (lastdf['fir_noadd_earn_percent']<-0.2 ) ])
    last_bigbig_kuisun_counts = len( lastdf[ (lastdf['fir_noadd_earn_percent']<-0.5 ) ])

    last_total_counts = len( lastdf)
    last_bigbig_earn_per = last_bigbig_earn_counts /last_total_counts  if last_total_counts!=0 else -10
    last_big_earn_per = last_big_earn_counts / last_total_counts  if last_total_counts!=0 else -10
    last_nor_earn_per = last_nor_earn_counts / last_total_counts if last_total_counts!=0 else -10
    last_nor_kuisun_per = last_nor_kuisun_counts /last_total_counts  if last_total_counts!=0 else -10
    last_big_kuisun_per= last_big_kuisun_counts / last_total_counts  if last_total_counts!=0 else -10
    last_bigbig_kuisun_per = last_bigbig_kuisun_counts / last_total_counts if last_total_counts!=0 else -10

    return (
        last_bigbig_earn_counts,
        last_big_earn_counts,
        last_nor_earn_counts,
        last_nor_kuisun_counts,
        last_big_kuisun_counts,
        last_bigbig_kuisun_counts,
        last_total_counts,
        last_bigbig_earn_per ,
        last_big_earn_per ,
        last_nor_earn_per ,
        last_nor_kuisun_per ,
        last_big_kuisun_per,
        last_bigbig_kuisun_per ,
    ) 



    
    return
def get_analyres(df,  dalao_address, now_unix_time):
    (last_03d_cost, last_03d_earn, last_03d_earnper, last_03d_difcost, last_03d_difearn, last_03d_difper, last_03d_costmedian, last_03d_costmean,    last_03d_trans , last_03d_mine_fir_earnper ,last_03d_mine_fir_earnper_dropmax, last_03d_mine_fir_earnper_droptwomax   ) = analysis_lastdays(
        df, now_unix_time=now_unix_time, intervaldays=3
    )
    (last_07d_cost, last_07d_earn, last_07d_earnper, last_07d_difcost, last_07d_difearn, last_07d_difper, last_07d_costmedian, last_07d_costmean,   last_07d_trans , last_07d_mine_fir_earnper ,last_07d_mine_fir_earnper_dropmax, last_07d_mine_fir_earnper_droptwomax  ) = analysis_lastdays(
        df, now_unix_time=now_unix_time, intervaldays=7
    )
    # (last_11d_cost, last_11d_earn, last_11d_earnper, last_11d_difcost, last_11d_difearn, last_11d_difper, last_11d_costmedian, last_11d_costmean,  last_11d_trans , last_11d_mine_fir_earnper ,last_11d_mine_fir_earnper_dropmax , last_11d_mine_fir_earnper_droptwomax ) = analysis_lastdays(
    #     df, now_unix_time=now_unix_time, intervaldays=11
    # )
    (last_15d_cost, last_15d_earn, last_15d_earnper, last_15d_difcost, last_15d_difearn, last_15d_difper, last_15d_costmedian, last_15d_costmean,   last_15d_trans , last_15d_mine_fir_earnper ,last_15d_mine_fir_earnper_dropmax , last_15d_mine_fir_earnper_droptwomax ) = analysis_lastdays(
        df, now_unix_time=now_unix_time, intervaldays=15
    )
    (last_30d_cost, last_30d_earn, last_30d_earnper, last_30d_difcost, last_30d_difearn, last_30d_difper, last_30d_costmedian, last_30d_costmean,  last_30d_trans , last_30d_mine_fir_earnper ,last_30d_mine_fir_earnper_dropmax , last_30d_mine_fir_earnper_droptwomax ) = analysis_lastdays(
        df, now_unix_time=now_unix_time, intervaldays=30
    )
	
    # # 去除所有daxin
    # df = df[df["isdaxin"] == "0"].reset_index(drop=True)

    (last_03d_cost_noaddouttoken, last_03d_earn_noaddouttoken, last_03d_earnper_noaddouttoken, last_03d_difcost_noaddouttoken, last_03d_difearn_noaddouttoken, last_03d_difper_noaddouttoken, last_03d_costmedian_noaddouttoken, last_03d_costmean_noaddouttoken,   last_03d_trans ,
     last_03d_mine_noadd_fir_earnper , last_03d_mine_noadd_fir_earnper_dropmax , last_03d_mine_noadd_fir_earnper_droptwomax ) = analysis_lastdays_noaddouttoken(
        df, now_unix_time=now_unix_time, intervaldays=3
    )
    (last_07d_cost_noaddouttoken, last_07d_earn_noaddouttoken, last_07d_earnper_noaddouttoken, last_07d_difcost_noaddouttoken, last_07d_difearn_noaddouttoken, last_07d_difper_noaddouttoken, last_07d_costmedian_noaddouttoken, last_07d_costmean_noaddouttoken,   last_07d_trans,
     last_07d_mine_noadd_fir_earnper , last_07d_mine_noadd_fir_earnper_dropmax , last_07d_mine_noadd_fir_earnper_droptwomax) = analysis_lastdays_noaddouttoken(
        df, now_unix_time=now_unix_time, intervaldays=7
    )
    # (last_11d_cost_noaddouttoken, last_11d_earn_noaddouttoken, last_11d_earnper_noaddouttoken, last_11d_difcost_noaddouttoken, last_11d_difearn_noaddouttoken, last_11d_difper_noaddouttoken, last_11d_costmedian_noaddouttoken, last_11d_costmean_noaddouttoken,    last_11d_trans,
    #  last_11d_mine_noadd_fir_earnper , last_11d_mine_noadd_fir_earnper_dropmax , last_11d_mine_noadd_fir_earnper_droptwomax) = analysis_lastdays_noaddouttoken(
    #     df, now_unix_time=now_unix_time, intervaldays=11
    # )
    (last_15d_cost_noaddouttoken, last_15d_earn_noaddouttoken, last_15d_earnper_noaddouttoken, last_15d_difcost_noaddouttoken, last_15d_difearn_noaddouttoken, last_15d_difper_noaddouttoken, last_15d_costmedian_noaddouttoken, last_15d_costmean_noaddouttoken,   last_15d_trans,
     last_15d_mine_noadd_fir_earnper , last_15d_mine_noadd_fir_earnper_dropmax , last_15d_mine_noadd_fir_earnper_droptwomax) = analysis_lastdays_noaddouttoken(
        df, now_unix_time=now_unix_time, intervaldays=15
    )

    (last_30d_cost_noaddouttoken, last_30d_earn_noaddouttoken, last_30d_earnper_noaddouttoken, last_30d_difcost_noaddouttoken, last_30d_difearn_noaddouttoken, last_30d_difper_noaddouttoken, last_30d_costmedian_noaddouttoken, last_30d_costmean_noaddouttoken,    last_30d_trans,
     last_30d_mine_noadd_fir_earnper , last_30d_mine_noadd_fir_earnper_dropmax , last_30d_mine_noadd_fir_earnper_droptwomax) = analysis_lastdays_noaddouttoken(
        df, now_unix_time=now_unix_time, intervaldays=30
    )
    (last_03d_bigbig_earn_counts, last_03d_big_earn_counts, last_03d_nor_earn_counts, last_03d_nor_kuisun_counts,last_03d_big_kuisun_counts,last_03d_bigbig_kuisun_counts ,last_03d_total_counts, 
    last_03d_bigbig_earn_per , last_03d_big_earn_per ,    last_03d_nor_earn_per ,    last_03d_nor_kuisun_per ,    last_03d_big_kuisun_per,    last_03d_bigbig_kuisun_per
      )  = analysis_lastdays_earn_kuisun_counts(
        df, now_unix_time=now_unix_time, intervaldays=3
    )
    (last_07d_bigbig_earn_counts, last_07d_big_earn_counts, last_07d_nor_earn_counts, last_07d_nor_kuisun_counts,last_07d_big_kuisun_counts,last_07d_bigbig_kuisun_counts ,last_07d_total_counts,
      last_07d_bigbig_earn_per , last_07d_big_earn_per , last_07d_nor_earn_per , last_07d_nor_kuisun_per , last_07d_big_kuisun_per, last_07d_bigbig_kuisun_per
    )  = analysis_lastdays_earn_kuisun_counts(
        df, now_unix_time=now_unix_time, intervaldays=7
    )
    # (last_11d_bigbig_earn_counts, last_11d_big_earn_counts, last_11d_nor_earn_counts, last_11d_nor_kuisun_counts,last_11d_big_kuisun_counts,last_11d_bigbig_kuisun_counts ,last_11d_total_counts,
    #  last_11d_bigbig_earn_per , last_11d_big_earn_per , last_11d_nor_earn_per , last_11d_nor_kuisun_per , last_11d_big_kuisun_per, last_11d_bigbig_kuisun_per
    #     ) = analysis_lastdays_earn_kuisun_counts(
    #     df, now_unix_time=now_unix_time, intervaldays=11
    # )
    (last_15d_bigbig_earn_counts, last_15d_big_earn_counts, last_15d_nor_earn_counts, last_15d_nor_kuisun_counts,last_15d_big_kuisun_counts,last_15d_bigbig_kuisun_counts ,last_15d_total_counts,
     last_15d_bigbig_earn_per ,  last_15d_big_earn_per , last_15d_nor_earn_per , last_15d_nor_kuisun_per , last_15d_big_kuisun_per, last_15d_bigbig_kuisun_per
        ) = analysis_lastdays_earn_kuisun_counts(
        df, now_unix_time=now_unix_time, intervaldays=15
    )

    (last_30d_bigbig_earn_counts, last_30d_big_earn_counts, last_30d_nor_earn_counts, last_30d_nor_kuisun_counts,last_30d_big_kuisun_counts,last_30d_bigbig_kuisun_counts ,last_30d_total_counts,
     last_30d_bigbig_earn_per , last_30d_big_earn_per , last_30d_nor_earn_per , last_30d_nor_kuisun_per , last_30d_big_kuisun_per, last_30d_bigbig_kuisun_per
        ) = analysis_lastdays_earn_kuisun_counts(
        df, now_unix_time=now_unix_time, intervaldays=30
    )
    dalao_rul =  f"https://solscan.io/account/{dalao_address}"
    
    analist = [
        dalao_address,
        dalao_rul,
        "",
        last_03d_cost,
        last_03d_earn,
        last_03d_earnper,
        last_03d_difcost,
        last_03d_difearn,
        last_03d_difper,
        last_03d_costmedian,
        last_03d_costmean,

        last_03d_cost_noaddouttoken,
        last_03d_earn_noaddouttoken,
        last_03d_earnper_noaddouttoken,
        # last_03d_difcost_noaddouttoken,
        # last_03d_difearn_noaddouttoken,
        # last_03d_difper_noaddouttoken,
        # last_03d_costmedian_noaddouttoken,
        # last_03d_costmean_noaddouttoken,
        last_03d_mine_fir_earnper,
        last_03d_mine_fir_earnper_dropmax,
        last_03d_mine_fir_earnper_droptwomax,
        last_03d_mine_noadd_fir_earnper ,
        last_03d_mine_noadd_fir_earnper_dropmax ,
        last_03d_mine_noadd_fir_earnper_droptwomax,
        last_03d_trans,

        last_07d_cost,
        last_07d_earn,
        last_07d_earnper,
        last_07d_difcost,
        last_07d_difearn,
        last_07d_difper,
        last_07d_costmedian,
        last_07d_costmean,

        last_07d_cost_noaddouttoken,
        last_07d_earn_noaddouttoken,
        last_07d_earnper_noaddouttoken,
        # last_07d_difcost_noaddouttoken,
        # last_07d_difearn_noaddouttoken,
        # last_07d_difper_noaddouttoken,
        # last_07d_costmedian_noaddouttoken,
        # last_07d_costmean_noaddouttoken,
        last_07d_mine_fir_earnper,
        last_07d_mine_fir_earnper_dropmax,
        last_07d_mine_fir_earnper_droptwomax,
        last_07d_mine_noadd_fir_earnper ,
        last_07d_mine_noadd_fir_earnper_dropmax ,
        last_07d_mine_noadd_fir_earnper_droptwomax,
        last_07d_trans,

        # last_11d_cost,
        # last_11d_earn,
        # last_11d_earnper,
        # last_11d_difcost,
        # last_11d_difearn,
        # last_11d_difper,
        # last_11d_costmedian,
        # last_11d_costmean,

        # last_11d_cost_noaddouttoken,
        # last_11d_earn_noaddouttoken,
        # last_11d_earnper_noaddouttoken,
        # # last_11d_difcost_noaddouttoken,
        # # last_11d_difearn_noaddouttoken,
        # # last_11d_difper_noaddouttoken,
        # # last_11d_costmedian_noaddouttoken,
        # # last_11d_costmean_noaddouttoken,
        # last_11d_mine_fir_earnper,
        # last_11d_mine_fir_earnper_dropmax,
        # last_11d_mine_fir_earnper_droptwomax,
        # last_11d_mine_noadd_fir_earnper , 
        # last_11d_mine_noadd_fir_earnper_dropmax , 
        # last_11d_mine_noadd_fir_earnper_droptwomax ,
        # last_11d_trans,


        last_15d_cost,
        last_15d_earn,
        last_15d_earnper,
        last_15d_difcost,
        last_15d_difearn,
        last_15d_difper,
        last_15d_costmedian,
        last_15d_costmean,

        last_15d_cost_noaddouttoken,
        last_15d_earn_noaddouttoken,
        last_15d_earnper_noaddouttoken,
        # last_15d_difcost_noaddouttoken,
        # last_15d_difearn_noaddouttoken,
        # last_15d_difper_noaddouttoken,
        # last_15d_costmedian_noaddouttoken,
        # last_15d_costmean_noaddouttoken,
        last_15d_mine_fir_earnper,
        last_15d_mine_fir_earnper_dropmax,
        last_15d_mine_fir_earnper_droptwomax,
        last_15d_mine_noadd_fir_earnper , 
        last_15d_mine_noadd_fir_earnper_dropmax , 
        last_15d_mine_noadd_fir_earnper_droptwomax,
        last_15d_trans,

        last_30d_cost,
        last_30d_earn,
        last_30d_earnper,
        last_30d_difcost,
        last_30d_difearn,
        last_30d_difper,
        last_30d_costmedian,
        last_30d_costmean,

        last_30d_cost_noaddouttoken,
        last_30d_earn_noaddouttoken,
        last_30d_earnper_noaddouttoken,
        # last_30d_difcost_noaddouttoken,
        # last_30d_difearn_noaddouttoken,
        # last_30d_difper_noaddouttoken,
        # last_30d_costmedian_noaddouttoken,
        # last_30d_costmean_noaddouttoken,
        last_30d_mine_fir_earnper,
        last_30d_mine_fir_earnper_dropmax,
        last_30d_mine_fir_earnper_droptwomax,
        last_30d_mine_noadd_fir_earnper , 
        last_30d_mine_noadd_fir_earnper_dropmax , 
        last_30d_mine_noadd_fir_earnper_droptwomax ,
        last_30d_trans,


        last_30d_earn-last_30d_earn_noaddouttoken,
        last_30d_mine_fir_earnper - last_30d_mine_noadd_fir_earnper,
    ]

    arr_earn_kuisun_counts=[
     dalao_address,
    dalao_rul,
    "",
    last_03d_bigbig_earn_counts, last_03d_big_earn_counts, last_03d_nor_earn_counts,
    last_03d_nor_kuisun_counts,last_03d_big_kuisun_counts,last_03d_bigbig_kuisun_counts ,
    last_03d_bigbig_earn_per,  last_03d_big_earn_per ,    last_03d_nor_earn_per ,    
    last_03d_nor_kuisun_per ,    last_03d_big_kuisun_per,    last_03d_bigbig_kuisun_per,
    last_03d_total_counts ,  

    last_07d_bigbig_earn_counts, last_07d_big_earn_counts, last_07d_nor_earn_counts, 
    last_07d_nor_kuisun_counts,last_07d_big_kuisun_counts,last_07d_bigbig_kuisun_counts ,
    last_07d_bigbig_earn_per , last_07d_big_earn_per , last_07d_nor_earn_per ,
    last_07d_nor_kuisun_per , last_07d_big_kuisun_per, last_07d_bigbig_kuisun_per,
    last_07d_total_counts  , 

    # last_11d_bigbig_earn_counts, last_11d_big_earn_counts, last_11d_nor_earn_counts,
    # last_11d_nor_kuisun_counts,last_11d_big_kuisun_counts,last_11d_bigbig_kuisun_counts ,
    # last_11d_bigbig_earn_per , last_11d_big_earn_per , last_11d_nor_earn_per ,
    # last_11d_nor_kuisun_per , last_11d_big_kuisun_per, last_11d_bigbig_kuisun_per,
	 
    # last_11d_total_counts   ,

    last_15d_bigbig_earn_counts, last_15d_big_earn_counts, last_15d_nor_earn_counts,
    last_15d_nor_kuisun_counts,last_15d_big_kuisun_counts,last_15d_bigbig_kuisun_counts ,
    last_15d_bigbig_earn_per ,  last_15d_big_earn_per , last_15d_nor_earn_per , 
    last_15d_nor_kuisun_per , last_15d_big_kuisun_per, last_15d_bigbig_kuisun_per,
    last_15d_total_counts  ,

    
    last_30d_bigbig_earn_counts, last_30d_big_earn_counts, last_30d_nor_earn_counts,
    last_30d_nor_kuisun_counts,last_30d_big_kuisun_counts,last_30d_bigbig_kuisun_counts ,
    last_30d_bigbig_earn_per , last_30d_big_earn_per , last_30d_nor_earn_per ,
    last_30d_nor_kuisun_per , last_30d_big_kuisun_per, last_30d_bigbig_kuisun_per,
	 
    last_30d_total_counts   ,

    ]



    global TotalAnalysis_list
    global total_arr_earn_kuisun
    TotalAnalysis_list.append(analist)
    total_arr_earn_kuisun.append(arr_earn_kuisun_counts)


def calute_days(df, now_unix_time):
    df["diffdays"] = 0
    # intervaldays_list = [15, 11, 7, 3]
    intervaldays_list = [30, 15, 7, 3]
    for intervaldays in intervaldays_list:
        df.loc[df["TokenFirstTime"] >=
               now_unix_time - 3600*24*intervaldays, "diffdays"] = intervaldays
    return df


def calucate_earnmain_dropoutoken(row):
    earnmain_amount_dropoutoken = decimal.Decimal(row['earn_main'])
    outtoken_per = decimal.Decimal(row["outtoken_per"])
    issellfir = row["issellfir"]

    # if outtoken_per >= 1.1 or outtoken_per == -10 
    if outtoken_per > 1 or issellfir==0:
        earnmain_amount_dropoutoken = decimal.Decimal(0)
    earnmain_amount_dropoutoken_str = '{0:.4f}'.format(
        earnmain_amount_dropoutoken)
    return float(earnmain_amount_dropoutoken_str)


def makeDexurl(row, dalao_address):
    tokenAddress = row['swap_tokenaddress']
    urlname = f"https://dexscreener.com/solana/{tokenAddress}?maker={dalao_address}"
    return '=HYPERLINK("{}","{}")'.format(urlname, "DEX/"+tokenAddress)


def get_ana_df(dalao_address, df, success_address_list, onetxhash_onerow_ana_df):
    onedalao_ana_df = df[onedalao_ana_columns].drop_duplicates(
    ).reset_index(drop=True)
    onedalao_ana_df.insert(
        loc=2, column="swap_tokenadd_dexurl", value="")

    onedalao_ana_df['swap_tokenadd_dexurl'] = onedalao_ana_df.apply(
        lambda row: makeDexurl(row, dalao_address), axis=1)
    onedalao_ana_df["FirstDateTime"] = pd.to_datetime(
        onedalao_ana_df['TokenFirstTime'], unit='s')
    # 如果outoken超了，earn_main_noaddouttoken 的值有两种处理方式
    # 一种设置为0 即为不亏不赚
    # 一种为全负  即为全亏了
    # onedalao_ana_df["earn_main_noaddouttoken"] = onedalao_ana_df.apply(
    #     lambda row: calucate_earnmain_dropoutoken(row), axis=1)

    get_analyres(df=onedalao_ana_df, dalao_address=dalao_address,
                 now_unix_time=now_unix_time)

    onedalao_ana_df = calute_days(
        df=onedalao_ana_df, now_unix_time=now_unix_time)

    handle_onedalao_ana_df = onedalao_ana_df[onedalao_ana_df['cost_main'] != 0].reset_index(
        drop=True)

    baseclass.makedirpath(baseclass.dalao_ana_fm_path / dalao_address)

    onedalao_ana_df.to_csv(baseclass.dalao_ana_fm_path /
                           dalao_address/f"analysisprofit_{dalao_address}.csv", index=False)
    handle_onedalao_ana_df.to_csv(baseclass.dalao_ana_fm_path /
                                  dalao_address/f"analysisprofit_handle_{dalao_address}.csv", index=False)
    onetxhash_onerow_ana_df.to_csv(baseclass.dalao_ana_fm_path /
                                   dalao_address/f"onetxhash_onerow_profit_{dalao_address}.csv", index=False)

    success_address_list.remove(dalao_address)


def get_profit_st(str_dalao_address):

    if not (baseclass.dalao_configtoken_st_solanafm_path /
            f"configtoken_{str_dalao_address}.csv").exists():
        return None
    # print(f"enter get_profit_st dalao_address= {str_dalao_address} \n", end='')
    df = pd.read_csv(baseclass.dalao_configtoken_st_solanafm_path /
                     f"configtoken_{str_dalao_address}.csv", dtype=object)
    #  timestamp	sign	source	destination	token	amount	swap_tokenadd	swap_eth_amount	swap_token_amount	token_idx  dalaofirsttimestamp
    df["timestamp"] = df["timestamp"].astype(int)
    df['dalaofirsttimestamp'] = pd.to_datetime(
        df['dalaofirsttimestamp'] )
    df["dexurl"] = df.apply(lambda ser: (f'https://dexscreener.com/solana/{ser["swap_tokenaddress"]}?maker={str_dalao_address}' ), axis=1)
    df["TokenFirstTime"] = df.groupby("token_idx")[
        "timestamp"].transform("min")
    df = calute_days(
        df=df, now_unix_time=now_unix_time)
    df = df.sort_values(by=["dalaofirsttimestamp", 'swap_tokenaddress', 'timestamp'], ascending=[
        False, True, True]).reset_index(drop=True)
    onetxhash_onerow_ana_df = df.copy()
    onetxhash_onerow_ana_df = onetxhash_onerow_ana_df[["timestamp", "TokenFirstTime", 
                                                       "sign", "swap_tokenaddress","dexurl","platform","swap_type",
                                                       "swap_eth_amount", "swap_token_amount",
                                                       "dalaofirsttimestamp","diffdays"]]

    onetxhash_onerow_ana_df = onetxhash_onerow_ana_df.astype(
        {'swap_eth_amount': float})
    # 计算一个txhash的 tokenamount swap 数目
    onetxhash_onerow_ana_df = get_txhash_tokenswap_amount(
        df=onetxhash_onerow_ana_df)
    # 计算一个txhash的sol swap 数目
    earnMain_df = (
        onetxhash_onerow_ana_df
        .groupby('sign')["swap_eth_amount"]
        .sum()
    )
    onetxhash_onerow_ana_df['swap_eth_amount'] = onetxhash_onerow_ana_df["sign"].map(
        earnMain_df)

    onetxhash_onerow_ana_df = onetxhash_onerow_ana_df.drop_duplicates().reset_index(drop=True)
    onetxhash_onerow_ana_df = get_tokenswap_amount(df=onetxhash_onerow_ana_df)
    onetxhash_onerow_ana_df = onetxhash_onerow_ana_df.sort_values(by=["dalaofirsttimestamp", 'swap_tokenaddress', 'timestamp'], ascending=[
        False, True, True]).reset_index(drop=True)
    onetxhash_onerow_ana_df = get_sol_profit(df=onetxhash_onerow_ana_df)

    onetxhash_onerow_ana_df["datetime"] = pd.to_datetime(
        onetxhash_onerow_ana_df["timestamp"], unit='s')

    onetxhash_onerow_ana_df=onetxhash_onerow_ana_df[onetxhash_onerow_ana_cols]
    onetxhash_onerow_ana_df.to_csv(
        baseclass.dalao_profit_st_fm_path / f"onetxhash_onerow_profit_{str_dalao_address}.csv", index=False)
    # onetxhash_onerow_ana_df=pd.DataFrame()
    def set_platform(gdf):
        if  "unknown" in  gdf["platform"]:
            gdf["platform"] =  "unknown" 
            print("unknow in plat")
        return gdf
    
    onetxhash_onerow_ana_df.groupby(by=["swap_tokenaddress"]).apply(lambda gdf : set_platform(gdf))                                                                  

    onetxhash_onerow_ana_dropdup_df = onetxhash_onerow_ana_df.drop_duplicates(subset=["swap_tokenaddress"]).reset_index(drop=True)
 
    onetxhash_onerow_ana_dropdup_df.to_csv(
        baseclass.dalao_profit_st_fm_path / f"onetxhash_onerow_profit_dropdup_{str_dalao_address}.csv", index=False)
    
    return onetxhash_onerow_ana_df


def get_dalaoaddress_list():
    df = pd.read_csv(baseclass.dalao_merge_path /
                     "filter_dalao.csv", dtype=object)
    arr_dalao_address = df["dalaoAddress"].tolist()
    return arr_dalao_address


def save_earn_kuisun_df():
     
    global total_arr_earn_kuisun
    totalana_earn_kuisun_df = pd.DataFrame(
        data=total_arr_earn_kuisun, columns=earn_kuisun_columns
    )
    totalana_earn_kuisun_df = totalana_earn_kuisun_df.round(4)
    totalana_earn_kuisun_df = totalana_earn_kuisun_df.sort_values(by=["add"], ascending=[
        True]).reset_index(drop=True)
    totalana_earn_kuisun_df.to_excel(
        baseclass.dalao_total_ana_fm_path/f"totalana_earn_kuisun_df.xlsx", index=False)
    
    return
def save_total_ana_df():
    global TotalAnalysis_list
    TotalAnalysis_df = pd.DataFrame(
        data=TotalAnalysis_list, columns=TotalAnalysis_columns
    )

    TotalAnalysis_df = TotalAnalysis_df.round(4)
    TotalAnalysis_df = TotalAnalysis_df.sort_values(by=["add"], ascending=[
        True]).reset_index(drop=True)
 
    TotalAnalysis_df.to_csv(
        baseclass.dalao_total_ana_fm_path/f"totalana.csv", index=False)

    TotalAnalysis_df.to_excel(
        baseclass.dalao_total_ana_fm_path/f"totalana.xlsx", index=False)

    # mine_fir_earnper_filter_mask = (
    #     (TotalAnalysis_df["15d_mine_fir_earnper"] >=
    #      0.8*TotalAnalysis_df["11d_mine_fir_earnper"])
    #     & (TotalAnalysis_df["11d_mine_fir_earnper"] >= 0.8*TotalAnalysis_df["07d_mine_fir_earnper"])
    # )
    # mine_fir_earnper_dropmax_filter_mask = (
    #     (TotalAnalysis_df["15d_mine_fir_earnper_dropmax"] >=
    #      0.8*TotalAnalysis_df["11d_mine_fir_earnper_dropmax"])
    #     & (TotalAnalysis_df["11d_mine_fir_earnper_dropmax"] >= 0.8*TotalAnalysis_df["07d_mine_fir_earnper_dropmax"])
    # )
    
    mine_noadd_fir_earnper_filter_mask = (
        (TotalAnalysis_df["30d_mine_noadd_fir_earnper"] >=
         0.8*TotalAnalysis_df["15d_mine_noadd_fir_earnper"])
        & (TotalAnalysis_df["15d_mine_noadd_fir_earnper"] >= 0.8*TotalAnalysis_df["07d_mine_noadd_fir_earnper"])
    )
   
    mine_noadd_fir_earnper_dropmax_filter_mask = (
        (TotalAnalysis_df["30d_mine_noadd_fir_earnper_dropmax"] >=
         0.8*TotalAnalysis_df["15d_mine_noadd_fir_earnper_dropmax"])
        & (TotalAnalysis_df["15d_mine_noadd_fir_earnper_dropmax"] >= 0.8*TotalAnalysis_df["07d_mine_noadd_fir_earnper_dropmax"])
    )

    filter_mask = (

        # mine_fir_earnper_filter_mask
        # | mine_fir_earnper_dropmax_filter_mask
          mine_noadd_fir_earnper_filter_mask
        | mine_noadd_fir_earnper_dropmax_filter_mask
    )
    increase_TotalAnalysis_df = TotalAnalysis_df[filter_mask].reset_index(
        drop=True)
    increase_TotalAnalysis_df.to_excel(
        baseclass.dalao_total_ana_fm_path/f"increase_totalana.xlsx", index=False)
    # last_07d_has_mask = (increase_TotalAnalysis_df["07d_trans"]== increase_TotalAnalysis_df["11d_trans"])
    # last_07d_increase_TotalAnalysis_df = increase_TotalAnalysis_df[last_07d_has_mask]
    increase_TotalAnalysis_df.to_excel(
        baseclass.dalao_total_ana_fm_path/f"increase_totalana_07d.xlsx", index=False)

def get_mul_profit_st():
    global arr_str_dalaoaddress
    success_address_list = arr_str_dalaoaddress.copy()
    for idx in range(0, len(arr_str_dalaoaddress), batchSize):
        thread_list = []
        for cur_idx in range(idx, min(idx+batchSize, len(arr_str_dalaoaddress))):
            thread = threading.Thread(
                target=get_one_profit_st,
                args=(arr_str_dalaoaddress[cur_idx],
                      success_address_list, cur_idx)
            )
            thread_list.append(thread)
        for thread in thread_list:
            thread.start()
        for thread in thread_list:
            thread.join()


def get_one_profit_st(dalao_address, success_address_list, cur_idx):
    try:
        df = None
        onetxhash_onerow_ana_df = None
        print(f"get_one_profit_st cur_idx={cur_idx} dalao_address={dalao_address}\n", end='')

        onetxhash_onerow_ana_df = get_profit_st(
            str_dalao_address=dalao_address)
        if onetxhash_onerow_ana_df is None:
            print(f"get_one_profit_st cur_idx={cur_idx} is None \n", end='')
            return
        get_ana_df(dalao_address=dalao_address, df=onetxhash_onerow_ana_df,
                success_address_list=success_address_list, onetxhash_onerow_ana_df=onetxhash_onerow_ana_df)
        print(f"cur_idx={cur_idx} end \n", end='')
        return
    except Exception as e:
        print(f"error_dalao_address={dalao_address}")
        raise

batchSize = 5
TotalAnalysis_list = []
total_arr_earn_kuisun =[]
now_unix_time = int(time.time())
arr_str_dalaoaddress = get_dalaoaddress_list()
arr_str_dalaoaddress = arr_str_dalaoaddress[0:450]
arr_str_dalaoaddress.append(baseclass.mywalletaddress)
# arr_str_dalaoaddress = ['H5P5xig8WjcDQrzyR4HaKcrg4hd2vh5DLPnFs4ypNE1X']
print(f"arr_str_dalaoaddress len= {len(arr_str_dalaoaddress)}")
get_mul_profit_st()
save_total_ana_df()
save_earn_kuisun_df()
print(f"arr_str_dalaoaddress len= {len(arr_str_dalaoaddress)} \n", end='')

print(f"{'{:<6}'.format('END')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")
