// use super::{
//     dec, ema, exists_record, limit_order_sell, rsi, select_filled_buy_orders, stoch_rsi,
//     supertrend, try_join_all, AllData, Arc, Client, ClientBuilder, EmaData, ExchangeInfo, Mutex,
//     RealtimePriceData, RoundingStrategy, RsiData, StochRsiData, SupertrendData, TradeFee,
//     insert_pre_suggested_coins, Decimal, FilteredData, decimal_add, decimal_sub
// };

// pub async fn list_up_for_buy(
//     alldata: AllData,
// ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//     // print rt_price for debugging
//     // let a = alldata.rt_price_30m_vec.iter().position(|a| a.0 == "BTCUSDT");
//     // println!("BTCUSDT: {:?}", alldata.rt_price_30m_vec[a.unwrap()].1.last().unwrap());

//     // 1st filtering: lookup tables if the tradepair is already there
//     let inspect_table_name_1 = String::from("buy_ordered_coin_list");
//     let inspect_table_name_2 = String::from("sell_ordered_coin_list");
//     let inspect_table_name_3 = String::from("pre_suggested_coin_list");
//     let inspect_table_name_4 = String::from("suggested_coin_list");

//     let mut filtered_data_1st: Vec<FilteredData> = Vec::new();
//     let mut filtered_data_1st_arc: Arc<Mutex<Vec<FilteredData>>> =
//         Arc::new(Mutex::new(filtered_data_1st));
//     let mut task_vec = Vec::new();

//     for symbol in &alldata.valid_symbol_vec {
//         let mut exists_condition_build = String::from("symbol=\'");
//         exists_condition_build.push_str(symbol.as_str());
//         exists_condition_build.push_str("\' AND registerer=");
//         exists_condition_build.push_str(3.to_string().as_str());
//         // exists_condition_build.push_str("\' AND close_time=");
//         // exists_condition_build.push_str(element.1.to_string().as_str());
//         let exists_condition = Some(exists_condition_build);
//         let exists_condition_c = exists_condition.clone();
//         let inspect_table_name_1_c = inspect_table_name_1.clone();
//         let inspect_table_name_2_c = inspect_table_name_2.clone();
//         let inspect_table_name_3_c = inspect_table_name_3.clone();
//         let inspect_table_name_4_c = inspect_table_name_4.clone();
//         let symbol_c = symbol.clone();
//         let filtered_data_1st_arc_c = Arc::clone(&filtered_data_1st_arc);
//         task_vec.push(tokio::spawn(async move {
//             let mut filtered_data = FilteredData::new();
//             let inspect_result_1 =
//                 exists_record(&inspect_table_name_1_c, &exists_condition_c).await;
//             let inspect_result_2 =
//                 exists_record(&inspect_table_name_2_c, &exists_condition_c).await;
//             let inspect_result_3 =
//                 exists_record(&inspect_table_name_3_c, &exists_condition_c).await;
//             let inspect_result_4 =
//                 exists_record(&inspect_table_name_4_c, &exists_condition_c).await;

//             if inspect_result_1 == false
//                 && inspect_result_2 == false
//                 && inspect_result_3 == false
//                 && inspect_result_4 == false
//             {
//                 let mut filtered_data_1st_lock = filtered_data_1st_arc_c.lock().await;

//                 filtered_data.symbol = symbol_c;

//                 filtered_data_1st_lock.push(filtered_data);
//             }
//         }));
//     }
//     try_join_all(task_vec).await?;

//     // 1st filtering: supertrend(ATR period 100, multiplier: 6.0, 30m close price), the area should be in UP area.
//     let mut filtered_2nd_symbols: Vec<(String, i64)> = Vec::new();
//     let mut filtered_2nd_symbols_arc: Arc<Mutex<Vec<(String, i64)>>> =
//         Arc::new(Mutex::new(filtered_2nd_symbols)); // (symbol, closetime)
//     let mut task_vec = Vec::new();
//     let valid_symbol_vec_c = alldata.valid_symbol_vec.clone();
//     for symbol in valid_symbol_vec_c {
//         let mut opclo_30m_vec: Vec<RealtimePriceData> = Vec::new();
//         let mut supertrend_vec: Vec<SupertrendData> = Vec::new();
//         let rt_price_30m_vec_c = alldata.rt_price_30m_vec.clone();
//         let filtered_2nd_symbols_arc_c = Arc::clone(&filtered_2nd_symbols_arc);
//         task_vec.push(tokio::spawn(async move {
//             let opclo_30m_option = rt_price_30m_vec_c.iter().position(|x| *x.0 == symbol);
//             let supertrend_option_30m =
//                 supertrend(&symbol, &rt_price_30m_vec_c, 100, 6.0, true).await;

//             if opclo_30m_option.is_some() && supertrend_option_30m.is_some() {
//                 opclo_30m_vec = rt_price_30m_vec_c[opclo_30m_option.unwrap()].1.clone();
//                 supertrend_vec = supertrend_option_30m.unwrap();

//                 if opclo_30m_vec.len() >= 3 && supertrend_vec.len() >= 3 {
//                     let supertrend_search_result = supertrend_vec.binary_search_by_key(
//                         &opclo_30m_vec.last().unwrap().close_time,
//                         |SupertrendData {
//                              band_value,
//                              signal,
//                              area,
//                              close_time,
//                          }| *close_time,
//                     );
//                     if supertrend_search_result.is_ok() {
//                         if supertrend_vec[supertrend_search_result.unwrap()]
//                             .area
//                             .contains("UP")
//                         {
//                             let mut filtered_2nd_symbols_lock =
//                                 filtered_2nd_symbols_arc_c.lock().await;
//                             filtered_2nd_symbols_lock
//                                 .push((symbol.clone(), opclo_30m_vec.last().unwrap().close_time));
//                         }
//                     }
//                 }
//             }
//         }));
//     }
//     try_join_all(task_vec).await?;

//     // 2nd filtering: lookup tables if the tradepair is already there
//     let inspect_table_name_1 = String::from("buy_ordered_coin_list");
//     let inspect_table_name_2 = String::from("sell_ordered_coin_list");
//     let inspect_table_name_3 = String::from("pre_suggested_coin_list");
//     let inspect_table_name_4 = String::from("suggested_coin_list");

//     let mut filtered_3rd_symbols: Vec<(String, i64)> = Vec::new();
//     let mut filtered_3rd_symbols_arc: Arc<Mutex<Vec<(String, i64)>>> =
//         Arc::new(Mutex::new(filtered_3rd_symbols)); // (symbol, closetime)
//     let mut task_vec = Vec::new();

//     let filtered_2nd_iter = filtered_2nd_symbols_arc.lock().await.clone().into_iter();
//     for element in filtered_2nd_iter {
//         let mut exists_condition_build = String::from("symbol=\'");
//         exists_condition_build.push_str(element.0.as_str());
//         exists_condition_build.push_str("\' AND registerer=");
//         exists_condition_build.push_str(3.to_string().as_str());
//         // exists_condition_build.push_str("\' AND close_time=");
//         // exists_condition_build.push_str(element.1.to_string().as_str());
//         let exists_condition = Some(exists_condition_build);
//         let exists_condition_c = exists_condition.clone();
//         let inspect_table_name_1_c = inspect_table_name_1.clone();
//         let inspect_table_name_2_c = inspect_table_name_2.clone();
//         let inspect_table_name_3_c = inspect_table_name_3.clone();
//         let inspect_table_name_4_c = inspect_table_name_4.clone();
//         let element_c = element.clone();
//         let filtered_3rd_symbols_arc_c = Arc::clone(&filtered_3rd_symbols_arc);
//         task_vec.push(tokio::spawn(async move {
//             let inspect_result_1 =
//                 exists_record(&inspect_table_name_1_c, &exists_condition_c).await;
//             let inspect_result_2 =
//                 exists_record(&inspect_table_name_2_c, &exists_condition_c).await;
//             let inspect_result_3 =
//                 exists_record(&inspect_table_name_3_c, &exists_condition_c).await;
//             let inspect_result_4 =
//                 exists_record(&inspect_table_name_4_c, &exists_condition_c).await;

//             if inspect_result_1 == false
//                 && inspect_result_2 == false
//                 && inspect_result_3 == false
//                 && inspect_result_4 == false
//             {
//                 let mut filtered_3rd_symbols_lock = filtered_3rd_symbols_arc_c.lock().await;
//                 filtered_3rd_symbols_lock.push(element_c);
//             }
//         }));
//     }
//     try_join_all(task_vec).await?;

//     // 3rd filtering: EMA30 > EMA 150
//     let filtered_3rd_symbols_c = filtered_3rd_symbols_arc.lock().await.clone();
//     let ema30_30m_data: Vec<(String, Vec<EmaData>)> =
//         ema(30, &alldata.rt_price_30m_vec, &filtered_3rd_symbols_c).await?;
//     let ema150_30m_data: Vec<(String, Vec<EmaData>)> =
//         ema(150, &alldata.rt_price_30m_vec, &filtered_3rd_symbols_c).await?;

//     let mut task_vec = Vec::new();
//     let mut filtered_4th_symbols: Vec<(String, i64)> = Vec::new();
//     let mut filtered_4th_symbols_arc: Arc<Mutex<Vec<(String, i64)>>> =
//         Arc::new(Mutex::new(filtered_4th_symbols)); // (symbol, closetime)
//     for element in filtered_3rd_symbols_c {
//         let mut ema30_30m_vec: Vec<EmaData> = Vec::new();
//         let mut ema150_30m_vec: Vec<EmaData> = Vec::new();
//         let ema30_30m_option = ema30_30m_data.iter().position(|x| *x.0 == element.0);
//         let ema30_30m_option_c = ema30_30m_option.clone();
//         let ema150_30m_option = ema150_30m_data.iter().position(|x| *x.0 == element.0);
//         let ema150_30m_option_c = ema150_30m_option.clone();
//         let element_c = element.clone();
//         let filtered_4th_symbols_arc_c = Arc::clone(&filtered_4th_symbols_arc);

//         if ema30_30m_option_c.is_some() && ema150_30m_option_c.is_some() {
//             ema30_30m_vec = ema30_30m_data[ema30_30m_option.unwrap()].1.clone();
//             ema150_30m_vec = ema150_30m_data[ema150_30m_option.unwrap()].1.clone();

//             if ema30_30m_vec.len() >= 10 && ema150_30m_vec.len() >= 10 {
//                 let ema30_30m_vec_c = ema30_30m_vec.clone();
//                 let ema150_30m_vec_c = ema150_30m_vec.clone();

//                 task_vec.push(tokio::spawn(async move {
//                     let ema30_search_result = ema30_30m_vec_c.binary_search_by_key(
//                         &element_c.1,
//                         |&EmaData {
//                              ema_value,
//                              close_time,
//                          }| close_time,
//                     );
//                     let ema150_search_result = ema150_30m_vec_c.binary_search_by_key(
//                         &element_c.1,
//                         |&EmaData {
//                              ema_value,
//                              close_time,
//                          }| close_time,
//                     );

//                     if ema30_search_result.is_ok() && ema150_search_result.is_ok() {
//                         if ema30_30m_vec_c[ema30_search_result.unwrap() - 3].ema_value
//                             > ema150_30m_vec_c[ema150_search_result.unwrap() - 3].ema_value
//                             && ema30_30m_vec_c[ema30_search_result.unwrap() - 2].ema_value
//                                 > ema150_30m_vec_c[ema150_search_result.unwrap() - 2].ema_value
//                             && ema30_30m_vec_c[ema30_search_result.unwrap() - 1].ema_value
//                                 > ema150_30m_vec_c[ema150_search_result.unwrap() - 1].ema_value
//                             && ema30_30m_vec_c[ema30_search_result.unwrap()].ema_value
//                                 > ema150_30m_vec_c[ema150_search_result.unwrap()].ema_value
//                             && ema30_30m_vec_c[ema30_search_result.unwrap()].ema_value
//                                 > ema30_30m_vec_c[ema30_search_result.unwrap() - 1].ema_value
//                             && ema30_30m_vec_c[ema30_search_result.unwrap() - 1].ema_value
//                                 > ema30_30m_vec_c[ema30_search_result.unwrap() - 2].ema_value
//                             && ema30_30m_vec_c[ema30_search_result.unwrap() - 2].ema_value
//                                 > ema30_30m_vec_c[ema30_search_result.unwrap() - 3].ema_value
//                         {
//                             let mut filtered_4th_symbols_lock =
//                                 filtered_4th_symbols_arc_c.lock().await;
//                             filtered_4th_symbols_lock.push(element_c);
//                         }
//                     }
//                 }));
//             }
//         }
//     }
//     try_join_all(task_vec).await?;

//     // 4th filtering: StochRSI (RSI length: 10, Stoch length: 10, smooth k: 3, smooth d: 3) 20 > k > kn-1 > kn-2 > kn-3,
//     let filtered_4th_symbol_c = filtered_4th_symbols_arc.lock().await.clone();
//     let mut rsi10_30m_data: Vec<(String, Vec<RsiData>)> =
//         rsi(10, &alldata.rt_price_30m_vec, &filtered_4th_symbol_c).await?;
//     let stoch_rsi_data = stoch_rsi(&rsi10_30m_data, 10, 3, 3).await?;
//     let mut stoch_rsi10_30m_vec: Vec<StochRsiData> = Vec::new();
//     let mut filtered_5th_symbols: Vec<(String, i64)> = Vec::new(); // (symbol, closetime)
//     for element in filtered_4th_symbol_c {
//         let stoch_rsi10_30m_option = stoch_rsi_data.iter().position(|x| *x.0 == element.0);

//         if stoch_rsi10_30m_option.is_some() {
//             stoch_rsi10_30m_vec = stoch_rsi_data[stoch_rsi10_30m_option.unwrap()].1.clone();

//             if stoch_rsi10_30m_vec.len() >= 3 {
//                 let stoch_rsi_search_result = stoch_rsi10_30m_vec
//                     .binary_search_by_key(&element.1, |&StochRsiData { k, d, close_time }| {
//                         close_time
//                     });
//                 if stoch_rsi_search_result.is_ok() {
//                     if 10.0 > stoch_rsi10_30m_vec[stoch_rsi_search_result.unwrap()].k
//                         && stoch_rsi10_30m_vec[stoch_rsi_search_result.unwrap()].k
//                             > stoch_rsi10_30m_vec[stoch_rsi_search_result.unwrap() - 1].k
//                         && stoch_rsi10_30m_vec[stoch_rsi_search_result.unwrap() - 1].k
//                             <= stoch_rsi10_30m_vec[stoch_rsi_search_result.unwrap() - 2].k
//                         && stoch_rsi10_30m_vec[stoch_rsi_search_result.unwrap() - 2].k
//                             <= stoch_rsi10_30m_vec[stoch_rsi_search_result.unwrap() - 3].k
//                     {
//                         filtered_5th_symbols.push(element);
//                     }
//                 }
//             }
//         }
//     }

//     // final job: adding price information to filtered results
//     let mut filtered_symbols: Vec<(String, i64, f64)> = Vec::new(); // (symbol, closetime, current price)
//     let mut filtered_symbols_arc = Arc::new(Mutex::new(filtered_symbols));
//     let mut task_vec = Vec::new();
//     for element in filtered_5th_symbols {
//         let mut filtered_symbols_arc_c = Arc::clone(&filtered_symbols_arc);
//         let rt_price_30m_vec_c = alldata.rt_price_30m_vec.clone();

//         let elememt_c = element.clone();
//         task_vec.push(tokio::spawn(async move {
//             let opclo_30m_option = rt_price_30m_vec_c.iter().position(|x| *x.0 == element.0);
//             if opclo_30m_option.is_some() {
//                 if rt_price_30m_vec_c[opclo_30m_option.unwrap()]
//                     .1
//                     .last()
//                     .is_some()
//                 {
//                     let mut filtered_symbols_lock: tokio::sync::MutexGuard<
//                         '_,
//                         Vec<(String, i64, f64)>,
//                     > = filtered_symbols_arc_c.lock().await;
//                     filtered_symbols_lock.push((
//                         elememt_c.0,
//                         elememt_c.1,
//                         rt_price_30m_vec_c[opclo_30m_option.unwrap()]
//                             .1
//                             .last()
//                             .unwrap()
//                             .close_price,
//                     ));
//                 }
//             }
//         }));
//     }

//     try_join_all(task_vec).await?;

//     // TODO: abnormal price filtering (too high current price)

//     // 6th filtering condition: MACD
//     // let mut opclo_30m_vec: Vec<RealtimePriceData> = Vec::new();
//     // let mut ema3_1d_vec: &Vec<EmaData> = &Vec::new();
//     // let mut ema10_1d_vec: &Vec<EmaData> = &Vec::new();

//     // let mut filtered_7th_symbols: Vec<(String, i64)> = Vec::new();  // (symbol, closetime)
//     // for element in filtered_6th_symbols {
//     //     let ema3_1d_option = alldata.ema3_1d_data.iter().position(|x| *x.0 == *element.0);
//     //     let ema10_1d_option = alldata.ema10_1d_data.iter().position(|x| *x.0 == *element.0);

//     //     if ema3_1d_option.is_some() && ema10_1d_option.is_some() {
//     //         ema3_1d_vec = &alldata.ema3_1d_data[ema3_1d_option.unwrap()].1;
//     //         ema10_1d_vec = &alldata.ema10_1d_data[ema10_1d_option.unwrap()].1;

//     //         if ema3_1d_vec.len() > 20 && ema10_1d_vec.len() > 20 {
//     //             let macd_vec = ema_macd(&ema3_1d_vec, &ema10_1d_vec, 10).await?;
//     //         //  let macd_search_result = macd_vec.binary_search_by_key(&element.1, |&EmaMacd{macd_value, close_time}|close_time);

//     //             // if macd_search_result.is_ok() {
//     //                 if macd_vec.last().unwrap().macd_value - macd_vec[macd_vec.len() -2].macd_value >= 0.0 {
//     //                     filtered_7th_symbols.push(element);
//     //                 }
//     //             // }
//     //         }
//     //     }
//     // }
//     let a = filtered_symbols_arc.lock().await.clone();
//     insert_pre_suggested_coins(3, false, &a, &alldata).await;

//     Ok(())
// }

// pub async fn list_up_for_sell(
//     all_data: &AllData,
//     exchange_info_vec: &Vec<ExchangeInfo>,
//     trade_fee_vec: &Vec<TradeFee>,
// ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//     let filled_buy_orders = select_filled_buy_orders(3).await?;

//     if !filled_buy_orders.is_empty() {
//         let client = ClientBuilder::new()
//             .timeout(tokio::time::Duration::from_millis(5000))
//             .build()
//             .unwrap();

//         let mut sell_order_count = 0;
//         for element in filled_buy_orders {
//             if element.used_usdt >= dec!(10.0) {
//                 // ignore coins having 10 usdt below because of not traded
//                 let sell_percent_for_uptrend = |z: f64| 0.94 * z - 0.5;

//                 let lot_step_size_option = exchange_info_vec
//                     .iter()
//                     .find(|exchange_info| exchange_info.symbol == element.symbol);
//                 let quote_commission_precision_option = exchange_info_vec
//                     .iter()
//                     .find(|exchange_info| exchange_info.symbol == element.symbol);

//                 let opclo_30m_option = all_data
//                     .rt_price_30m_vec
//                     .iter()
//                     .position(|x| *x.0 == element.symbol);

//                 if lot_step_size_option.is_some()
//                     && quote_commission_precision_option.is_some()
//                     && opclo_30m_option.is_some()
//                 {
//                     let lot_step_size = lot_step_size_option.unwrap().stepsize;
//                     let quote_commission_precision = quote_commission_precision_option
//                         .unwrap()
//                         .quote_commission_precision;
//                     let base_qty_to_be_ordered =
//                         element.base_qty_fee_adjusted.round_dp_with_strategy(
//                             lot_step_size.normalize().scale(),
//                             RoundingStrategy::ToZero,
//                         );

//                     let mut opclo_30m_vec = all_data.rt_price_30m_vec[opclo_30m_option.unwrap()]
//                         .1
//                         .clone();

//                     opclo_30m_vec.pop();
//                     opclo_30m_vec.reverse();
//                     let mut opclo_sample_length: usize = 50; // 50 candle samsples
//                     let nbr_of_exclusive: usize = 5;
//                     opclo_30m_vec.truncate(opclo_sample_length);
//                     opclo_30m_vec.sort_by(|a, b| {
//                         (a.high_price - a.low_price).total_cmp(&(b.high_price - b.low_price))
//                     });
//                     opclo_30m_vec.truncate(opclo_sample_length - nbr_of_exclusive);
//                     opclo_sample_length -= nbr_of_exclusive;

//                     let mut sum_amplitude_candles = 0.0;
//                     let mut sum_ratio_amp_body = 0.0;
//                     for element in &opclo_30m_vec {
//                         sum_amplitude_candles +=
//                             ((element.high_price / element.low_price) - 1.0) * 100.0;
//                         sum_ratio_amp_body += (element.close_price - element.open_price).abs()
//                             / (element.high_price - element.low_price);
//                     }
//                     let average_amplitude = sum_amplitude_candles / opclo_sample_length as f64; // percent unit
//                     let average_ratio_amp_body = sum_ratio_amp_body / opclo_sample_length as f64;

//                     let mut amplitude_variance = 0.0;
//                     for element in &opclo_30m_vec {
//                         amplitude_variance += ((((element.high_price / element.low_price) - 1.0)
//                             * 100.0)
//                             - average_amplitude)
//                             .powi(2);
//                     }
//                     amplitude_variance = amplitude_variance / (opclo_sample_length - 1) as f64;
//                     let standard_deviation_amplitude = amplitude_variance.sqrt();

//                     // let target_profit_percent = average_amplitude + (standard_deviation_amplitude * (average_ratio_amp_body));
//                     let target_profit_percent = |multiplier: f64| -> f64 {
//                         if multiplier < 0.0 {
//                             ((average_amplitude) * multiplier)
//                                 - (standard_deviation_amplitude * 2.0) // 2.0 sigma (recommand: 0.5 ~ 2.0(patient & greedy))
//                         } else {
//                             ((average_amplitude) * multiplier)
//                                 + (standard_deviation_amplitude * 2.0) // 2.0 sigma (recommand: 0.5 ~ 2.0(patient & greedy))
//                         }
//                     };

//                     if element.is_long == 0 || element.is_long == 1 {
//                         if element.pure_profit_percent >= 0.0 {
//                             let mut is_sell = false;
//                             if element.maximum_profit_percent >= target_profit_percent(5.0) + 0.2
//                                 && element.pure_profit_percent >= target_profit_percent(5.0) + 0.2
//                             {
//                                 println!(
//                                     "Selling {} 500% target_profit_percent: {:.3}",
//                                     element.symbol, element.pure_profit_percent
//                                 );
//                                 is_sell = true;
//                             } else if element.pure_profit_percent >= 7.0 {
//                                 println!("Selling {} 7% profit_percent", element.symbol);
//                                 is_sell = true;
//                             }

//                             if is_sell == true {
//                                 // let mut sell_price_ahead: Decimal = Decimal::new(14, 8);
//                                 // sell_price_ahead = decimal_mul(decimal_add(decimal_mul(decimal_mul(rust_decimal::Decimal::from_f64(element.pure_profit_percent).unwrap(), dec!(0.01)), dec!(0.97)), dec!(1)), element.buy_price).round_dp_with_strategy(2, RoundingStrategy::ToZero);
//                                 limit_order_sell(
//                                     &element,
//                                     element.current_price,
//                                     base_qty_to_be_ordered,
//                                     &client,
//                                     &exchange_info_vec,
//                                     &trade_fee_vec,
//                                 )
//                                 .await;
//                             }
//                         } else {
//                             let mut is_sell = false;
//                             if element.pure_profit_percent <= target_profit_percent(-2.5) - 0.2
//                             // -0.2 means about total trade fees.
//                             {
//                                 println!(
//                                     "Selling {} -250% target_profit_percent: {:.3}",
//                                     element.symbol, element.pure_profit_percent
//                                 );
//                                 is_sell = true;
//                             } else if element.pure_profit_percent <= -5.0 {
//                                 println!("selling {} -5.0% profit", element.symbol);
//                                 is_sell = true;
//                             }

//                             if is_sell == true {
//                                 limit_order_sell(
//                                     &element,
//                                     element.current_price,
//                                     base_qty_to_be_ordered,
//                                     &client,
//                                     &exchange_info_vec,
//                                     &trade_fee_vec,
//                                 )
//                                 .await;
//                             }
//                         }
//                     }
//                 }
//             }
//         }
//     }

//     Ok(())
// }
