import pandas as pd
import sys
import matplotlib.pyplot as plt
import math
chicang_file = ''
df_chouma = None
sum_neg_hold = 0
sum_pos_hold = 0
def set_text(ax):
    variable_values = {
         'sum_pos': round(sum_pos_hold,1),
    'sum_neg': round(sum_neg_hold,1),
   
    'total': round(sum_pos_hold - sum_neg_hold,1)
    }

    # 设置文本的位置（例如右上角）
    text_position = (0.8, 0.9)  # 根据你的图表调整这个位置

    # 在指定位置添加文本
    offset = 0
    for key, value in variable_values.items():
        text = f'{key}: {value}'
        ax.text(text_position[0], text_position[1] - offset, text,transform=ax.transAxes, fontsize=10, color='black', 
                bbox=dict(facecolor='lightgrey', edgecolor='black', boxstyle='round,pad=0.5'))
        offset += 0.07  # 每次向下移动一行


def calculate_midpoint(interval):
    return (interval.left + interval.right) / 2

def draw_chouma():
    global df_chouma ,chicang_file
    df_grouped = df_chouma.groupby('avg_b_pri').sum()['chicang'].reset_index()
   
    max_pri = df_chouma['avg_b_pri'].max()
    min_pri = df_chouma['avg_b_pri'].min()

 
    # 自定义价格区间
    price_range = [pri*0.5 for pri in range(math.floor(min_pri),math.ceil(max_pri)*2)]
 
    # # 根据价格区间计算每个区间的总持仓量
    df_grouped['区间'] = pd.cut(df_grouped['avg_b_pri'], bins=price_range)
 
    grouped_by_interval = df_grouped.groupby('区间').sum()
  
    grouped_by_interval = grouped_by_interval.reset_index()
    grouped_by_interval['mid_pri'] = grouped_by_interval['区间'].apply(calculate_midpoint)
   
    grouped_by_interval.set_index(['区间'],inplace=True)
   
   
    # 绘制筹码分布图
    fig, ax = plt.subplots(figsize=(10, 6))
    # ax.bar(grouped_by_interval['mid_pri'], grouped_by_interval['chicang'],   align='center', color='skyblue')
    grouped_by_interval['chicang'].plot(kind='bar', ax=ax, color='skyblue')
    # 设置图表标题和标签
    ax.set_title('chouma-fenbu')
    ax.set_xlabel('chichang-pri')
    ax.set_ylabel('chicang-amount')
    plt.xticks(rotation=45)
   

    plt.ylim(0, 400)
    set_text(ax=ax)
    # plt.yticks(np.arange(0, 401, 50))
 
    # 保存图像到文件
    
    output_image_path =  chicang_file.split('_')[-1].replace('.csv','') + f'.png'  # 替换为你希望保存图像的路径和文件名
    plt.savefig(output_image_path, bbox_inches='tight', dpi=300)  # 使用高分辨率保存图像
    
    


def get_chouma_chicang():
    global chicang_file,df_chouma
    global sum_neg_hold ,sum_pos_hold
    df = pd.read_csv(chicang_file)
    df_neg_hold = df[df['li_lun_hold']<0  ].reset_index(drop=True)
    df_pos_hold = df[df['li_lun_hold']>0].reset_index(drop=True)
    sum_neg_hold = abs(df_neg_hold['li_lun_hold'].sum())
    sum_pos_hold = abs(df_pos_hold['li_lun_hold'].sum())
    df_pos_hold['chicang'] = df_pos_hold['li_lun_hold'] 

    df_chouma = df_pos_hold


# swap_trader_id,li_lun_hold,token_b_M,token_s_M,eth_b,eth_s,b_count,s_count,avg_b_pri,avg_s_pri

if __name__ == "__main__":
 
    if len(sys.argv)<2:
        print("args queshao ")
        sys.exit(1)
    chicang_file = sys.argv[1]
    get_chouma_chicang()
    draw_chouma()
 