Browse Source

修改为百分比导出

gepangpang 1 year ago
parent
commit
a6552dd30e

+ 2 - 0
config_balance.toml.sample

@@ -12,6 +12,8 @@ range_time = ["2023-12-20 18:00:00", "2023-12-26 10:00:00"]
 count_range_time = ["2023-12-25 10:00:00", "2023-12-26 10:00:00"]
 # 是否只导出汇总
 is_total = true
+# 收益率起始值
+start_earnings = 0.0
 # 配置导出表格模式(1:按小时导出,2:按余额变动导出)
 export_mode = 1
 # 导出路径(不填则为默认路径"./")

+ 8 - 6
src/export_balance.rs

@@ -2,6 +2,7 @@ use std::collections::{BTreeMap};
 use std::str::FromStr;
 use chrono::NaiveDateTime;
 use rust_decimal::Decimal;
+use rust_decimal::prelude::ToPrimitive;
 use rust_decimal_macros::dec;
 use tracing::{error, info};
 use crate::{export_template};
@@ -122,7 +123,7 @@ pub async fn export_balance(config_info: BalanceConfigInfo) {
 
                     let mut bybit_exc = BybitSwapRest::new(false, account_info.clone());
 
-                    let data = bybit_exc.get_account_transaction_log(start_time*1000, end_time*1000).await;
+                    let data = bybit_exc.get_account_transaction_log(start_time * 1000, end_time * 1000).await;
 
                     // info!("请求完成{:?}",data.clone());
                     if data.code.as_str() == "200" {
@@ -199,7 +200,7 @@ pub async fn export_balance(config_info: BalanceConfigInfo) {
     count_time_list.insert(0, count_start_time);
     count_time_list.push(count_end_time);
     let count_balance_info = supply_balance(all_account_balance_info.clone(), count_time_list.clone());
-    let statistic_result = statistic_balance(count_balance_info.clone(), count_start_time.clone(), count_end_time.clone());
+    let statistic_result = statistic_balance(count_balance_info.clone(), count_start_time.clone(), count_end_time.clone(), config_info.clone());
 
     // 根据小时填充
     let mut last_timestamp: i64 = -1;
@@ -222,7 +223,7 @@ pub async fn export_balance(config_info: BalanceConfigInfo) {
     };
 }
 
-pub fn statistic_balance(balance_info: Vec<Vec<String>>, count_start_time: i64, end_start_time: i64) -> String {
+pub fn statistic_balance(balance_info: Vec<Vec<String>>, count_start_time: i64, end_start_time: i64, config: BalanceConfigInfo) -> String {
     let mut max_withdrawal = dec!(0);
     let mut max_total_withdrawal = dec!(0);
     let mut total_income = dec!(0);
@@ -244,7 +245,7 @@ pub fn statistic_balance(balance_info: Vec<Vec<String>>, count_start_time: i64,
                 min_price = present_price;
                 continue;
             }
-            let present_withdrawal = ((Decimal::ONE - (min_price / max_price)) * dec!(100)).round_dp(2);
+            let present_withdrawal = ((max_price - min_price) / max_price * dec!(100)).round_dp(2);
             if present_withdrawal > withdrawal { withdrawal = present_withdrawal }
 
             if max_price > present_price && present_price < min_price {
@@ -257,12 +258,13 @@ pub fn statistic_balance(balance_info: Vec<Vec<String>>, count_start_time: i64,
             max_total_withdrawal = withdrawal;
             let present = Decimal::from_str(&balance_info[0][4]).unwrap();
             let past = Decimal::from_str(&balance_info[balance_info.len() - 1][4]).unwrap();
-            total_income = (((past / present) - Decimal::ONE) * dec!(100)).round_dp(2);
+            total_income = ((past - present) / present * dec!(100)).round_dp(2);
         }
     }
     let start_time = NaiveDateTime::from_timestamp_millis((count_start_time + 8 * 3600) * 1000).unwrap().format("%d日%H点").to_string();
     let end_time = NaiveDateTime::from_timestamp_millis((end_start_time + 8 * 3600) * 1000).unwrap().format("%d日%H点").to_string();
-    format!("{}到{},总收益约为{}%,最大回撤约为{}%,其中单个账号最大回撤约为{}%。", start_time, end_time, total_income, max_total_withdrawal, max_withdrawal)
+    let all_income = config.start_earnings + total_income.to_f64().unwrap();
+    format!("总收益约为:{}%<br/>{}到{},总收益约为{}%,最大回撤约为{}%,其中单个账号最大回撤约为{}%。", all_income, start_time, end_time, total_income, max_total_withdrawal, max_withdrawal)
 }
 
 pub fn supply_balance(source_balance_info: BTreeMap<String, Vec<Vec<String>>>, time_slicer: Vec<i64>) -> Vec<Vec<String>> {

+ 18 - 4
src/export_template/template_balance.rs

@@ -3,6 +3,8 @@ use std::fs::File;
 use std::io::Write;
 use chrono::NaiveDateTime;
 use handlebars::Handlebars;
+use rust_decimal::Decimal;
+use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
 use serde_json::json;
 use tracing::info;
 use crate::utils::utils::{BalanceConfigInfo};
@@ -24,6 +26,10 @@ pub fn export_html(config: BalanceConfigInfo, acc_name_all: &Vec<String>, x_time
     }
     //每个账号的数据
     let mut map: BTreeMap<String, Vec<f64>> = BTreeMap::new();
+    let mut capital_info: BTreeMap<String, f64> = Default::default();
+    for acc_name in acc_name_all.clone() {
+        capital_info.insert(acc_name.parse().unwrap(), 0.0);
+    }
     for acc_name in acc_name_all.clone() {
         let mut pr_data: Vec<f64> = vec![];
         let z = acc_name.clone();
@@ -35,7 +41,11 @@ pub fn export_html(config: BalanceConfigInfo, acc_name_all: &Vec<String>, x_time
         for data in data_list.clone() {
             if data[0].clone().as_str() == key {
                 let pr = data[4].clone().parse::<f64>().unwrap();
-                pr_data.push(pr);
+                if capital_info[key] == 0.0 { capital_info.insert(key.parse().unwrap(), pr); }
+                let earnings = Decimal::from_f64((pr - capital_info[key]) / capital_info[key] * 100.0).unwrap();
+                let show_earnings = earnings.to_f64().unwrap() + config.start_earnings;
+                pr_data.push(show_earnings);
+                // pr_data.push(pr);
             }
         }
         map.insert(key.to_string(), pr_data);
@@ -50,7 +60,6 @@ pub fn export_html(config: BalanceConfigInfo, acc_name_all: &Vec<String>, x_time
     let json = json!({
         "data":series_array
     });
-
     let series_str = format!("{}", json["data"]);
 
     let data = serde_json::json!({
@@ -76,7 +85,7 @@ pub fn export_html(config: BalanceConfigInfo, acc_name_all: &Vec<String>, x_time
                 #main {
                     margin: 50px auto 0;
                     width: calc(100vw - 100px);
-                    height: calc(100vh - 100px);
+                    height: calc(100vh - 150px);
                 }
                 .info_wp{
                     padding: 0 40px;
@@ -85,7 +94,7 @@ pub fn export_html(config: BalanceConfigInfo, acc_name_all: &Vec<String>, x_time
         </head>
         <body>
             <div id="main"></div>
-            <div class="info_wp">{{statistic_result}}</div>
+            <div class="info_wp">{{{statistic_result}}}</div>
         </body>
         <script>
             var exchangeColor = {binance: '#F4BC0C', gate: '#0068FF', okx: '#171F30'};
@@ -119,6 +128,11 @@ pub fn export_html(config: BalanceConfigInfo, acc_name_all: &Vec<String>, x_time
                   },
                   yAxis: {
                     type: 'value',
+                    axisLabel: {
+                        formatter: (value, index) => {
+                            return `${value}%`;
+                        }
+                    },
                     scale: true
                   },
                   series: "# + format!("{}", series_str).as_ref() + r#"

+ 3 - 3
src/swap_bybit/bybit_swap_rest_utils.rs

@@ -88,7 +88,7 @@ impl BybitSwapRest {
         data
     }
     //賬戶的交易日誌。
-    pub async fn get_account_transaction_log(&mut self,startTime:i64,endTime:i64) -> Response {
+    pub async fn get_account_transaction_log(&mut self, start_time: i64, end_time: i64) -> Response {
         let mut params = serde_json::json!({
             "accountType":"UNIFIED",
             "category":"linear",
@@ -96,8 +96,8 @@ impl BybitSwapRest {
          });
         // params["startTime"] = serde_json::json!(1703124000000 as i64);
         // params["endTime"] = serde_json::json!(1703664000000  as i64);
-        params["startTime"] = serde_json::json!(startTime);
-        params["endTime"] = serde_json::json!(endTime);
+        params["startTime"] = serde_json::json!(start_time);
+        params["endTime"] = serde_json::json!(end_time);
         let data = self.request("GET".to_string(),
                                 "/v5".to_string(),
                                 "/account/transaction-log".to_string(),

+ 2 - 0
src/utils/utils.rs

@@ -68,6 +68,7 @@ pub fn get_ticker_config_info(file_path: &str) -> TickerConfigInfo {
 pub struct BalanceConfigInfo {
     pub is_export: bool,
     pub is_total: bool,
+    pub start_earnings: f64,
     pub proxy_address: String,
     pub account_list: Vec<Vec<String>>,
     pub exchanges: Vec<String>,
@@ -83,6 +84,7 @@ impl BalanceConfigInfo {
         BalanceConfigInfo {
             is_export: false,
             is_total: true,
+            start_earnings: 0.0,
             proxy_address: "".to_string(),
             account_list: vec![],
             exchanges: vec![],