

# https://dexscreener.com/solana?rankBy=trendingScoreH24&order=desc&minLiq=50000&minAge=36

# 将油猴脚本获取的top trader
from base_class import BaseVariableFunction
from base_class import *
baseclass = BaseVariableFunction(__file__)

old_print = print


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


print = timestamped_print
 
baseclass.makedirpath(baseclass.dalao_tran_defined_path)
baseclass.makedirpath(baseclass.dalao_merge_defined_path)

 

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

def makescreenurl( urlname,urlparam):
    # pairAddress = series[address_str]
    urlname = urlname + urlparam
    return '=HYPERLINK("{}","{}")'.format(urlname, urlname)

def fun(gdf  ):
      
    # Maker = gdf['MAKER'].tolist()[0]
    gdf["FirstSwaptime"] = gdf["DATE"].min()
    gdf["buy_counts"] = len(gdf)
    
    return gdf
     
        
import re
def filter_simple_dalao():

    res_df = None
    big_amount_df = None
    global arr_token_address

    for tokenadd in arr_token_address:
     
        df_raydium =None
        df =None
  
        if (baseclass.dalao_tran_defined_path /  f"{tokenadd}_defined.xlsx").exists():
            continue
        
        if ( baseclass.dalao_ori_tran_defined_path / f"{tokenadd}_raydium.csv").exists():
            df_raydium =  pd.read_csv(
            baseclass.dalao_ori_tran_defined_path / f"{tokenadd}_raydium.csv", dtype=object)
            df_raydium =df_raydium.drop_duplicates().reset_index(drop=True)
            df_raydium["DATE"] = pd.to_datetime(df_raydium["DATE"], format='%Y-%m-%d %H:%M:%S')
            
            df_raydium=df_raydium.sort_values(by=["DATE"],ascending=[True])
 
            df_raydium=df_raydium[[
                'DATE',
                'TYPE',
                'SOL',
                'Token',
                'MAKER',
                'TXN',
                "PRICE",
                 ]]
                    
 
        df = pd.concat([  df_raydium  ], ignore_index=True)
        df["PRICE"] = df["PRICE"].astype(float)
    
        df=df.sort_values(by=["DATE"],ascending=[True])
        df = df[df['TYPE'].isin(['Buy', 'Sell'])].reset_index(drop=True)
        # df.to_excel(baseclass.dalao_merge_path/f"total_dalao_txn_{tokenadd}.xlsx",index=False)
        
        print(f"enter {tokenadd}")

        df["isNormal"] = "-1"
        df["TokenAddress"] = tokenadd
        

        df = df.groupby(by=['MAKER']).apply(
            lambda gdf: fun(gdf )).reset_index(drop=True)
         
        
        df =df.drop_duplicates(subset=["MAKER"]).reset_index(drop=True)
        # 示例 获取结果如下 https://www.defined.fi/sol/D6NdKrKNQPmRZCCnG1GqXtF7MMoHB7qR6GU5TkG59Qz1?maker=3ACp4T3ptTdayzWryEhT65NKZSKLjwXviBjWEy54aFdW 
        df['DefinedURL'] = df.apply(lambda ser: makescreenurl(
        "https://www.defined.fi/sol/", f"{ser['TokenAddress']}?maker={ser['MAKER']}"), axis=1)
            
        df =df[ [ 
                 "FirstSwaptime",
                'SOL',
                'Token',
                'MAKER',
                'TXN',
                "PRICE",
                "TokenAddress",
                "buy_counts",
                "isNormal",
                "DefinedURL"
                ] ]
        df.to_excel(baseclass.dalao_tran_defined_path /  f"{tokenadd}_defined.xlsx",index=False )
        
        
        
        
 
 
    return

csv_file_list = [f for f in os.listdir(
    baseclass.dalao_ori_tran_defined_path) if f.endswith(".csv") ]
arr_token_address = [tokenadd.split("_")[0] for tokenadd in csv_file_list  ]
arr_token_address=list(set(arr_token_address))


print("arr_token_address= ",arr_token_address)

filter_simple_dalao()

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