Apply Cargo fmt

This commit is contained in:
Sik Yoon 2023-11-19 01:58:09 +09:00
parent 8a53e18553
commit 5b7c4a9acb
21 changed files with 306 additions and 265 deletions

View File

@ -1,6 +1,7 @@
// assets_managing_team manages [asset_manage_announcement], [kelly_criterion], and[wallet] ([wallet_testnet] as well)
use crate::coex::exchange_team::*;
use crate::coex::order_team::{DBlist, SellHistoryList};
use crate::database_control::*;
use crate::decimal_funcs::*;
use crate::RunningMode::*;
@ -10,7 +11,6 @@ use rust_decimal::{prelude::ToPrimitive, Decimal, RoundingStrategy};
use rust_decimal_macros::dec;
use serde_json::{Result, Value};
use sqlx::FromRow;
use crate::coex::order_team::{DBlist, SellHistoryList};
#[derive(Debug, FromRow)]
pub struct AchievementEvaluationInfo {
@ -196,12 +196,16 @@ pub async fn update_current_total_usdt() {
let asset_info = select_asset_manage_announcement().await;
let achievement_evaluation = select_achievement_evaluation().await;
let balance = decimal_sub(achievement_evaluation.usdt_profit, achievement_evaluation.invested_usdt);
let balance = decimal_sub(
achievement_evaluation.usdt_profit,
achievement_evaluation.invested_usdt,
);
let current_total_usdt = decimal_add(asset_info.initial_usdt, balance);
let profit = decimal_sub(
decimal_div(current_total_usdt, asset_info.initial_usdt),
dec!(1));
dec!(1),
);
update_values = vec![
(
@ -290,16 +294,27 @@ pub async fn update_kelly_criterion() -> Result<()> {
.await
.unwrap();
let least_number = 50; // the least number of sell hostory to calculate kelly criterion
// FIXME: let least_number = 50;
let least_number = 1000000000; // the least number of sell hostory to calculate kelly criterion
if sell_history_vec.len() >= least_number {
let lose_collection_vec = sell_history_vec.iter().filter(|&a| a.pure_profit_percent < 0.0).collect::<Vec<_>>();
let win_collection_vec = sell_history_vec.iter().filter(|&a| a.pure_profit_percent >= 0.0).collect::<Vec<_>>();
let win_rate: f64 = (win_collection_vec.len() as f64)/(sell_history_vec.len() as f64);
let lose_collection_vec = sell_history_vec
.iter()
.filter(|&a| a.pure_profit_percent < 0.0)
.collect::<Vec<_>>();
let win_collection_vec = sell_history_vec
.iter()
.filter(|&a| a.pure_profit_percent >= 0.0)
.collect::<Vec<_>>();
let win_rate: f64 = (win_collection_vec.len() as f64) / (sell_history_vec.len() as f64);
let lose_rate: f64 = 1.0 - win_rate;
let loss_sum = lose_collection_vec.iter().fold(0.0, |acc, x| acc + x.pure_profit_percent);
let loss_sum = lose_collection_vec
.iter()
.fold(0.0, |acc, x| acc + x.pure_profit_percent);
let loss_rate_avg = (loss_sum * 0.01) / (lose_collection_vec.len() as f64) * -1.0;
let profit_sum = win_collection_vec.iter().fold(0.0, |acc, x| acc + x.pure_profit_percent);
let profit_sum = win_collection_vec
.iter()
.fold(0.0, |acc, x| acc + x.pure_profit_percent);
let profit_rate_avg = (profit_sum * 0.01) / (win_collection_vec.len() as f64);
let betting_rate = (win_rate / loss_rate_avg) - (lose_rate / profit_rate_avg);
@ -307,13 +322,12 @@ pub async fn update_kelly_criterion() -> Result<()> {
// update kelly_criterion
let update_table_name = String::from("kelly_criterion");
let update_value = vec![
(String::from("betting_rate"), betting_rate.to_string()),
(String::from("win_rate"), win_rate.to_string()),
(String::from("lose_rate"), lose_rate.to_string()),
(String::from("profit_rate"), profit_rate_avg.to_string()),
(String::from("loss_rate"), loss_rate_avg.to_string()),
]
;
(String::from("betting_rate"), betting_rate.to_string()),
(String::from("win_rate"), win_rate.to_string()),
(String::from("lose_rate"), lose_rate.to_string()),
(String::from("profit_rate"), profit_rate_avg.to_string()),
(String::from("loss_rate"), loss_rate_avg.to_string()),
];
let update_condition = vec![(String::from("id"), String::from("1"))];
update_record3(&update_table_name, &update_value, &update_condition)
.await
@ -378,15 +392,20 @@ pub async fn set_available_usdt() {
let kelly_criterion_info = select_kelly_criterion().await;
let mut available_usdt: Decimal;
if kelly_criterion_info.betting_rate >= 5.0 && kelly_criterion_info.betting_rate < 100.0 {;
available_usdt = decimal_mul(asset_info.current_total_usdt, rust_decimal::prelude::FromPrimitive::from_f64(
kelly_criterion_info.betting_rate * 0.01,
)
.unwrap());
if kelly_criterion_info.betting_rate >= 5.0 && kelly_criterion_info.betting_rate < 100.0 {
available_usdt = decimal_mul(
asset_info.current_total_usdt,
rust_decimal::prelude::FromPrimitive::from_f64(
kelly_criterion_info.betting_rate * 0.01,
)
.unwrap(),
);
} else if kelly_criterion_info.betting_rate >= 100.0 {
available_usdt = asset_info.current_total_usdt;
} else { // default: 5% of current_total_usdt
available_usdt = decimal_mul(asset_info.current_total_usdt, dec!(0.05));
} else {
// default: 5% of current_total_usdt
// FIXME: dec!(0.05)
available_usdt = decimal_mul(asset_info.current_total_usdt, dec!(1));
}
let unit_trade_usdt = asset_info.unit_trade_usdt;
@ -563,9 +582,14 @@ pub async fn select_achievement_evaluation() -> AchievementEvaluationInfo {
let columns = String::from("*");
let condition = None;
// FIXME: this code should be general
let select_result = select_record(&table_name, &columns, &condition, &achievement_evaluation_info)
.await
.unwrap();
let select_result = select_record(
&table_name,
&columns,
&condition,
&achievement_evaluation_info,
)
.await
.unwrap();
let result_vec = &select_result[2]; //strategist #3
achievement_evaluation_info.strategist = result_vec.strategist;

View File

@ -1,10 +1,10 @@
use crate::coex::assets_managing_team::*;
use crate::coex::order_team::*;
use crate::strategy_team::AllData;
use crate::coin_health_check_team::request_others::{CoinPriceData, ExchangeInfo, TradeFee};
use crate::database_control::*;
use crate::decimal_funcs::{decimal, decimal_add, decimal_div, decimal_mul, decimal_sub};
use crate::signal_association::signal_decision::*;
use crate::strategy_team::AllData;
use reqwest::{Client, ClientBuilder};
use rust_decimal::{prelude::FromPrimitive, prelude::ToPrimitive, Decimal, RoundingStrategy};
use rust_decimal_macros::dec;
@ -196,7 +196,7 @@ pub struct MarketCapIndex {
impl DBlist for MarketCapIndex {
fn new() -> MarketCapIndex {
let a = MarketCapIndex {
let a = MarketCapIndex {
market_cap_index: 0.0,
minimum: 0.0,
maximum: 0.0,
@ -224,12 +224,12 @@ pub async fn buy_coin(
// filtering symbols to buy
for element in &suggested_coin {
if element.already_buy == 0
&& server_epoch - element.registered_server_epoch <= 300_000
if element.already_buy == 0 && server_epoch - element.registered_server_epoch <= 300_000
// 300_000 (300 secs = 5 mins)
{
filtered_suggested_coin_vec.push(element);
} else if server_epoch - element.registered_server_epoch >= 5_400_000 { // 30mins * 3
} else if server_epoch - element.registered_server_epoch >= 5_400_000 {
// 30mins * 3
delete_condition.push_str("id = ");
delete_condition.push_str(element.id.to_string().as_str());
delete_condition.push_str(" OR ");
@ -255,14 +255,13 @@ pub async fn buy_coin(
.iter()
.position(|TradeFee| TradeFee.symbol == element.symbol);
if exchange_info_result.is_some()
&& trade_fee_result.is_some()
{
let lot_step_size = exchange_info_vec[exchange_info_result.unwrap()].stepsize;
if exchange_info_result.is_some() && trade_fee_result.is_some() {
let lot_step_size =
exchange_info_vec[exchange_info_result.unwrap()].stepsize;
let tick_size = exchange_info_vec[exchange_info_result.unwrap()].ticksize;
let base_commission_precision = exchange_info_vec[exchange_info_result
.unwrap()]
.base_commission_precision;
let base_commission_precision = exchange_info_vec
[exchange_info_result.unwrap()]
.base_commission_precision;
let trade_fee = trade_fee_vec[trade_fee_result.unwrap()].takercommission;
// buy the suggested coin and transfer it into [buy_ordered_coin_list]

View File

@ -11,11 +11,11 @@ use crate::URL_TEST;
// use crates
use crate::coex::assets_managing_team::*;
use crate::coex::exchange_team::*;
use crate::strategy_team::{AllData, TimeData};
use crate::coin_health_check_team::request_others::{CoinPriceData, ExchangeInfo, TradeFee};
use crate::database_control::*;
use crate::decimal_funcs::*;
use crate::signal_association::signal_decision::*;
use crate::strategy_team::{AllData, TimeData};
use crate::value_estimation_team::datapoints::price_data::RealtimePriceData;
use crate::value_estimation_team::indicators::ema::EmaData;
use crate::value_estimation_team::indicators::sma::SmaData;
@ -605,30 +605,36 @@ async fn update_repeat_task(
// to get quote_commission_precision
let trade_fee = trade_fee_vec[trade_fee_result.unwrap()].takercommission;
let lot_step_size = exchange_info_vec[lot_step_size_result.unwrap()].stepsize;
let quote_commission_precision = exchange_info_vec[quote_commission_precision_result
.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 quote_commission_precision = exchange_info_vec
[quote_commission_precision_result.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 expected_get_usdt = decimal_mul(
decimal_mul(base_qty_to_be_ordered, price)
.round_dp_with_strategy(quote_commission_precision, RoundingStrategy::ToZero),
decimal_mul(base_qty_to_be_ordered, price).round_dp_with_strategy(
quote_commission_precision,
RoundingStrategy::ToZero,
),
decimal_sub(dec!(1), trade_fee),
);
let pure_profit_percent =
((expected_get_usdt.to_f64().unwrap() / element.used_usdt.to_f64().unwrap()) - 1.0)
* 100.0;
let pure_profit_percent = ((expected_get_usdt.to_f64().unwrap()
/ element.used_usdt.to_f64().unwrap())
- 1.0)
* 100.0;
update_record_build.push(element.id.to_string()); // id
update_record_build.push(price.to_string()); // current_price
update_record_build.push(expected_get_usdt.to_string()); //expected_get_usdt
update_record_build.push(decimal_sub(expected_get_usdt, element.used_usdt).to_string()); // expected_usdt_profit
update_record_build
.push(decimal_sub(expected_get_usdt, element.used_usdt).to_string()); // expected_usdt_profit
update_record_build.push(pure_profit_percent.to_string()); // pure_profit_percent
if element.minimum_profit_percent > pure_profit_percent {
update_record_build.push(pure_profit_percent.to_string()); // minimum_profit_percent
update_record_build.push(pure_profit_percent.to_string());
// minimum_profit_percent
} else if pure_profit_percent >= 0.0 {
update_record_build.push(0.0.to_string()); // minimum_profit_percent
} else {
@ -637,7 +643,8 @@ async fn update_repeat_task(
}
if element.maximum_profit_percent < pure_profit_percent {
update_record_build.push(pure_profit_percent.to_string()); // maximum_profit_percent
update_record_build.push(pure_profit_percent.to_string());
// maximum_profit_percent
} else if pure_profit_percent <= 0.0 {
update_record_build.push(0.0.to_string()); // maximum_profit_percent
} else {
@ -2089,7 +2096,9 @@ async fn get_timestamp() -> String {
}
// parameter 0: select all registerers
pub async fn select_filled_buy_orders(registerer: u32) -> Result<Vec<BuyOrderedCoinList>, Box<dyn std::error::Error + Send + Sync>> {
pub async fn select_filled_buy_orders(
registerer: u32,
) -> Result<Vec<BuyOrderedCoinList>, Box<dyn std::error::Error + Send + Sync>> {
let select_table_name = String::from("buy_ordered_coin_list");
let select_columns = String::from("*");
let mut select_condition_build = String::from("WHERE (status = 'FILLED' or status = 'SIMUL')");
@ -2115,7 +2124,6 @@ pub async fn select_filled_buy_orders(registerer: u32) -> Result<Vec<BuyOrderedC
eprint!("select_filled_buy_order() error!");
Err("error")?
}
}
// select open buy orders (NEW, Partially Filled)

View File

@ -1,4 +1,5 @@
use crate::coin_health_check_team::{request_candles::*, request_others::ExchangeInfo};
use crate::decimal_funcs::*;
use crate::RunningMode::*;
use crate::{database_control::*, RUNNING_MODE};
use hex::ToHex;
@ -6,7 +7,6 @@ use hmac_sha256::HMAC;
use reqwest::{Client, ClientBuilder, Response};
use rust_decimal::{prelude::ToPrimitive, Decimal};
use rust_decimal_macros::dec;
use crate::decimal_funcs::*;
use serde::Deserialize;
use serde_json::Value;
use sqlx::{Error, FromRow};
@ -27,11 +27,14 @@ pub async fn initialize_valid_usde_trade() -> Result<(), Box<dyn std::error::Err
symbol: String,
}
let mut usdt_trades = UsdtTrades { symbol: String::new()};
let mut usdt_trades = UsdtTrades {
symbol: String::new(),
};
let fetch_table_name = String::from("all_24h_change");
let column_name = String::from("symbol");
let mut condition_build = String::from("WHERE symbol LIKE '%USDT' AND symbol NOT LIKE '%DOWNUSDT'");
let mut condition_build =
String::from("WHERE symbol LIKE '%USDT' AND symbol NOT LIKE '%DOWNUSDT'");
condition_build.push_str(" AND symbol NOT LIKE '%UPUSDT' AND firstId >= 0 AND lastId >= 0");
condition_build.push_str(" AND bidPrice > 0");
condition_build.push_str(" AND bidQty > 0");
@ -62,7 +65,8 @@ pub async fn initialize_valid_usde_trade() -> Result<(), Box<dyn std::error::Err
let condition = Some(condition_build);
// get valid usdt trades
let usdt_trades = select_record(&fetch_table_name, &column_name, &condition, &usdt_trades).await?;
let usdt_trades =
select_record(&fetch_table_name, &column_name, &condition, &usdt_trades).await?;
// update valid usdt trades
let table_name = String::from("valid_usdt_trades");
@ -87,14 +91,18 @@ pub async fn collect_valid_usde_trade(
#[derive(Debug, FromRow)]
struct UsdtTrades {
symbol: String,
weightedavgprice: f64
weightedavgprice: f64,
}
let mut usdt_trades = UsdtTrades { symbol: String::new(), weightedavgprice:0.0 };
let mut usdt_trades = UsdtTrades {
symbol: String::new(),
weightedavgprice: 0.0,
};
let fetch_table_name = String::from("all_24h_change");
let column_name = String::from("symbol, weightedAvgPrice");
let mut condition_build = String::from("WHERE symbol LIKE '%USDT' AND symbol NOT LIKE '%DOWNUSDT'");
let mut condition_build =
String::from("WHERE symbol LIKE '%USDT' AND symbol NOT LIKE '%DOWNUSDT'");
condition_build.push_str(" AND symbol NOT LIKE '%UPUSDT' AND firstId >= 0 AND lastId >= 0");
condition_build.push_str(" AND bidPrice > 0");
condition_build.push_str(" AND bidQty > 0");
@ -126,7 +134,8 @@ pub async fn collect_valid_usde_trade(
let condition = Some(condition_build);
// get valid usdt trades
let usdt_trades = select_record(&fetch_table_name, &column_name, &condition, &usdt_trades).await?;
let usdt_trades =
select_record(&fetch_table_name, &column_name, &condition, &usdt_trades).await?;
// filtering usdt trades
let mut filtered_usdt_trades: Vec<String> = Vec::new();
@ -138,7 +147,9 @@ pub async fn collect_valid_usde_trade(
.position(|ExchangeInfo| ExchangeInfo.symbol == usdt_trade.symbol);
if step_size_result.is_some() {
let avg_price: Decimal = rust_decimal::prelude::FromPrimitive::from_f64(usdt_trade.weightedavgprice).unwrap();
let avg_price: Decimal =
rust_decimal::prelude::FromPrimitive::from_f64(usdt_trade.weightedavgprice)
.unwrap();
let step_size = exchange_info_vec[step_size_result.unwrap()].stepsize;
let step_price = decimal_mul(step_size, avg_price);
let unit_trade_usdt = crate::coex::assets_managing_team::get_unit_trade_usdt().await;

View File

@ -1,8 +1,8 @@
use crate::coex::assets_managing_team;
use crate::coex::order_team;
use crate::coex::order_team::{BuyOrderedCoinList, SellOrderedCoinList};
use crate::coin_health_check_team::*;
use crate::coin_health_check_team::request_others::ExchangeInfo;
use crate::coin_health_check_team::*;
use crate::database_control::*;
use crate::time_checking_team::{UserTime, *};
use crate::RunningMode::*;
@ -15,7 +15,6 @@ use sqlx::FromRow;
use std::{io, io::Write, path::Path, process::Stdio};
use tokio::{fs::*, io::ErrorKind, process::Command, task::JoinHandle, time::*};
const STRATEGIST_NUMBER: u32 = 16;
pub async fn initialization() {
@ -240,8 +239,8 @@ async fn initialize_database() {
}
}
delete_all_rows(&table_name)
.await
.expect("Failed to delete rows!");
.await
.expect("Failed to delete rows!");
println!("Ok");
}
@ -270,8 +269,8 @@ async fn initialize_database() {
}
}
delete_all_rows(&table_name)
.await
.expect("Failed to delete rows!");
.await
.expect("Failed to delete rows!");
monitors::initialize_valid_usde_trade().await;
println!("Ok");
@ -983,7 +982,7 @@ async fn initialize_database() {
}
if RUNNING_MODE == SIMUL {
assets_managing_team::add_extra_usdt(dec!(2200.0)).await;
assets_managing_team::add_extra_usdt(dec!(10000000000.0)).await;
assets_managing_team::update_current_total_usdt().await;
} else {
let mut table_name = String::new();

View File

@ -28,9 +28,9 @@ pub mod coex;
pub mod coin_health_check_team;
pub mod database_control;
pub mod decimal_funcs;
pub mod initialization;
pub mod server_health_check_team;
pub mod signal_association;
pub mod strategy_team;
pub mod time_checking_team;
pub mod value_estimation_team;
pub mod strategy_team;
pub mod initialization;

View File

@ -1,11 +1,11 @@
#![allow(unused)]
#![allow(warnings)]
use crate::strategy_team::AllData;
use crate::coin_health_check_team::*;
use crate::request_candles::CandleData;
use crate::request_others::{CoinPriceData, ExchangeInfo, TradeFee};
use crate::server_health_check_team::ServerHealth;
use crate::strategy_team::AllData;
use crate::time_checking_team::UserTime;
use crate::value_estimation_team::datapoints::price_data::RealtimePriceData;
use reqwest::{Client, ClientBuilder};
@ -204,7 +204,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("*** REAL MODE ***");
} else if RUNNING_MODE == RunningMode::TEST {
println!("*** TEST MODE ***");
} else if RUNNING_MODE == RunningMode::SIMUL {
} else if RUNNING_MODE == RunningMode::SIMUL {
println!("*** SIMULATION MODE ***");
}
@ -556,9 +556,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
match result {
Ok(T) => {
tx_exchange_info_data.send_modify(|vec| *vec = exchange_info_data_temp);
tx_task3
.send(3)
.expect("The mpsc channel has been closed.");
tx_task3.send(3).expect("The mpsc channel has been closed.");
}
Err(E) => {}
}
@ -586,8 +584,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(T) => {
let exchange_info_vec = rx5_exchange_info_data.borrow().clone();
let mut valid_usdt_trade_vec_temp: Vec<String> = Vec::new();
let result =
monitors::collect_valid_usde_trade(&mut valid_usdt_trade_vec_temp, &exchange_info_vec).await;
let result = monitors::collect_valid_usde_trade(
&mut valid_usdt_trade_vec_temp,
&exchange_info_vec,
)
.await;
match result {
Ok(T) => {
@ -716,7 +717,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
if tx_rt_price_30m_vec.is_closed() {
eprintln!("tx_rt_price_30m_vec has been closed!");
} else {
tx_rt_price_30m_vec.send_modify(|vec| *vec = rt_price_30m_vec_write_temp);
tx_rt_price_30m_vec
.send_modify(|vec| *vec = rt_price_30m_vec_write_temp);
}
}
Err(E) => {}
@ -813,7 +815,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// sleep as much as the loop recurs per 10 seconds, expecting child threads will have finished within 10 seconds.
elapsed_time = instant.elapsed().as_millis();
if 30_000 > elapsed_time { // 10_000 for major trade
if 30_000 > elapsed_time {
// 10_000 for major trade
sleep(Duration::from_millis((30_000 - elapsed_time) as u64)).await;
}
}
@ -827,8 +830,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let instant = Instant::now();
let mut candle_30m_vec_temp: Vec<(String, Vec<CandleData>)> = Vec::new();
let result =
request_candles::fetch_candle_delay(&interval, &mut candle_30m_vec_temp).await;
request_candles::fetch_candle_delay(&interval, &mut candle_30m_vec_temp).await;
// request_candles::fetch_candle_parallel(&interval, &mut candle_30m_vec_temp).await;
match result {
@ -840,7 +842,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
// sleep as much as the loop recurs per 60 seconds, expecting child threads will have finished within 60 seconds.
elapsed_time = instant.elapsed().as_millis();
if 60_000 > elapsed_time { //60_000
if 60_000 > elapsed_time {
//60_000
sleep(Duration::from_millis((60_000 - elapsed_time) as u64)).await;
}
}
@ -1015,7 +1018,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
all_data.rt_price_1w_vec = rx3_rt_price_1w_vec.borrow().clone();
all_data.rt_price_1mon_vec = rx3_rt_price_1mon_vec.borrow().clone();
let result = strategy_team::strategy_manager::execute_list_up_for_buy(&all_data).await;
let result =
strategy_team::strategy_manager::execute_list_up_for_buy(&all_data).await;
match result {
Ok(T) => {
@ -1090,7 +1094,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
all_data.rt_price_1w_vec = rx4_rt_price_1w_vec.borrow().clone();
all_data.rt_price_1mon_vec = rx4_rt_price_1mon_vec.borrow().clone();
let result = strategy_team::strategy_manager::execute_list_up_for_sell(&all_data, &exchange_info_vec, &trade_fee_vec).await;
let result = strategy_team::strategy_manager::execute_list_up_for_sell(
&all_data,
&exchange_info_vec,
&trade_fee_vec,
)
.await;
match result {
Ok(T) => {
@ -1149,11 +1158,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let instant = Instant::now();
let exchange_info_vec = rx_exchange_info_data.borrow().clone();
let trade_fee_vec = rx_tradefee_vec.borrow().clone();
let result = coex::exchange_team::buy_coin(
&exchange_info_vec,
&trade_fee_vec,
)
.await;
let result =
coex::exchange_team::buy_coin(&exchange_info_vec, &trade_fee_vec).await;
// send Task#0 a message to notify running on
match result {
@ -1183,11 +1189,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let exchange_info_vec = rx_exchange_info_data.borrow().clone();
let trade_fee_vec = rx_tradefee_vec.borrow().clone();
// let result = coex::exchange_team::buy_coin_for_test(&client, &coin_price_vec, &exchange_info_vec, &trade_fee_vec).await;
let result = coex::exchange_team::buy_coin(
&exchange_info_vec,
&trade_fee_vec,
)
.await;
let result = coex::exchange_team::buy_coin(&exchange_info_vec, &trade_fee_vec).await;
// send Task#0 a message to notify running on
match result {
@ -1431,8 +1433,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut elapsed_time = 0;
loop {
let instant = Instant::now();
let result =
coex::assets_managing_team::update_kelly_criterion().await;
let result = coex::assets_managing_team::update_kelly_criterion().await;
// send Task#0 a message to notify running on
match result {

View File

@ -41,10 +41,7 @@ pub async fn market_cap_index() -> Result<(), Box<dyn std::error::Error + Send +
// JSON Parsing
let mut v: Value = serde_json::from_str(text.as_str()).unwrap();
if v
.as_object()
.unwrap()
.get("data").is_none() {
if v.as_object().unwrap().get("data").is_none() {
return Err("Err")?;
}

View File

@ -1,31 +1,31 @@
pub mod strategy_manager;
pub mod strategy_001;
pub mod strategy_002;
pub mod strategy_003;
pub mod strategy_004;
pub mod strategy_005;
pub mod strategy_006;
pub mod strategy_manager;
use std::{sync::Arc};
use crate::coex::order_team::{limit_order_sell, select_filled_buy_orders};
use crate::coin_health_check_team::request_others::{ExchangeInfo, TradeFee};
use crate::database_control::*;
use crate::value_estimation_team::datapoints::price_data::RealtimePriceData;
use crate::value_estimation_team::indicators::macd::{ema_macd, EmaMacd};
use crate::value_estimation_team::indicators::rsi::{rsi, RsiData};
use crate::value_estimation_team::indicators::sma::{sma, SmaData};
use crate::value_estimation_team::indicators::ema::{ema, EmaData};
use crate::value_estimation_team::indicators::bollingerband::{bollingerband, BollingerBandData};
use crate::value_estimation_team::indicators::stoch_rsi::{stoch_rsi, StochRsiData};
use crate::value_estimation_team::indicators::supertrend::{supertrend, SupertrendData};
use crate::value_estimation_team::indicators::ema::{ema, EmaData};
use crate::value_estimation_team::indicators::heatmap_volume::{
heatmap_volume, HeatMapLevel, HeatmapVolumeData,
};
use crate::coex::order_team::{limit_order_sell, select_filled_buy_orders};
use crate::coin_health_check_team::request_others::{ExchangeInfo, TradeFee};
use crate::value_estimation_team::indicators::macd::{ema_macd, EmaMacd};
use crate::value_estimation_team::indicators::rsi::{rsi, RsiData};
use crate::value_estimation_team::indicators::sma::{sma, SmaData};
use crate::value_estimation_team::indicators::stoch_rsi::{stoch_rsi, StochRsiData};
use crate::value_estimation_team::indicators::supertrend::{supertrend, SupertrendData};
use futures::future::try_join_all;
use reqwest::{Client, ClientBuilder};
use rust_decimal::{prelude::FromPrimitive, prelude::ToPrimitive, Decimal, RoundingStrategy};
use rust_decimal_macros::dec;
use sqlx::FromRow;
use std::sync::Arc;
use tokio::sync::Mutex;
#[derive(Debug)]

View File

@ -1,4 +1,8 @@
use super::{limit_order_sell, AllData, RealtimePriceData, Mutex, Arc, try_join_all, exists_record, StochRsiData, EmaData, SupertrendData, RsiData, stoch_rsi, ema, rsi, supertrend, select_filled_buy_orders, ExchangeInfo, TradeFee, Client, ClientBuilder, dec, RoundingStrategy};
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,
};
pub async fn list_up_for_buy(
alldata: &AllData,
@ -105,18 +109,10 @@ pub async fn list_up_for_buy(
// 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 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();
@ -144,26 +140,33 @@ pub async fn list_up_for_buy(
let ema30_search_result = ema30_30m_vec_c.binary_search_by_key(
&element_c.1,
|&EmaData {
ema_value,
close_time,
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,
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
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;
@ -178,12 +181,8 @@ pub async fn list_up_for_buy(
// 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 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)
@ -194,19 +193,19 @@ pub async fn list_up_for_buy(
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,
);
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 {
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);
}
}
@ -339,7 +338,9 @@ pub async fn list_up_for_sell(
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.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;
@ -367,13 +368,14 @@ pub async fn list_up_for_sell(
// 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))
((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))
((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;
@ -382,16 +384,11 @@ pub async fn list_up_for_sell(
{
println!(
"Selling {} 500% target_profit_percent: {:.3}",
element.symbol,
element.pure_profit_percent
element.symbol, element.pure_profit_percent
);
is_sell = true;
} else if element.pure_profit_percent >= 7.0
{
println!(
"Selling {} 7% profit_percent",
element.symbol
);
} else if element.pure_profit_percent >= 7.0 {
println!("Selling {} 7% profit_percent", element.symbol);
is_sell = true;
}
@ -410,25 +407,21 @@ pub async fn list_up_for_sell(
}
} 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.
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
element.symbol, element.pure_profit_percent
);
is_sell = true;
} else if element.pure_profit_percent <= -5.0
{
println!(
"selling {} -5.0% profit",
element.symbol
);
} 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(
limit_order_sell(
&element,
element.current_price,
base_qty_to_be_ordered,

View File

@ -6,9 +6,12 @@ use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;
use serde::Deserialize;
use tokio::time::{sleep, Duration, Instant};
use super::{
exists_record, insert_one_record, try_select_record, AllData, ExchangeInfo, FromRow,
RealtimePriceData, TradeFee,
};
use crate::signal_association::signal_decision::*;
use super::{AllData, RealtimePriceData, exists_record, try_select_record, insert_one_record, FromRow, ExchangeInfo, TradeFee};
use tokio::time::{sleep, Duration, Instant};
#[derive(Debug, FromRow)]
struct ServerEpoch {
@ -41,10 +44,14 @@ pub async fn execute_list_up_for_buy(
pub async fn execute_list_up_for_sell(
all_data: &AllData,
exchange_info_vec: &Vec<ExchangeInfo>,
trade_fee_vec: &Vec<TradeFee>
trade_fee_vec: &Vec<TradeFee>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
crate::strategy_team::strategy_003::list_up_for_sell(all_data, exchange_info_vec, trade_fee_vec).await?;
crate::strategy_team::strategy_003::list_up_for_sell(
all_data,
exchange_info_vec,
trade_fee_vec,
)
.await?;
Ok(())
}
@ -649,4 +656,3 @@ pub async fn insert_pre_suggested_coins(
Ok(())
}

View File

@ -4,10 +4,10 @@
use crate::database_control::*;
use crate::value_estimation_team::datapoints::price_data::RealtimePriceData;
use csv::{DeserializeRecordsIter, StringRecord};
use futures::future::try_join_all;
use serde::Deserialize;
use sqlx::FromRow;
use std::f64::NAN;
use futures::future::try_join_all;
use std::sync::Arc;
use tokio::{fs::*, io::AsyncWriteExt, sync::Mutex, time::*};
@ -39,7 +39,6 @@ pub async fn rsi(
let mut task_vec = Vec::new();
for element in filtered_symbols {
let element_c = element.clone();
let rsi_data_wrapper_arc_c = Arc::clone(&rsi_data_wrapper_arc);
let symbol_search_result = input_rt_data.iter().position(|x| x.0 == *element_c.0);
@ -135,8 +134,8 @@ pub async fn rsi(
prev_avg_ups = current_avg_ups;
prev_avg_downs = current_avg_downs;
let rs =
current_avg_ups.unwrap() / (current_avg_downs.unwrap() + 0.00000001); // 0.00000001 is used to avoid division by 0
let rs = current_avg_ups.unwrap()
/ (current_avg_downs.unwrap() + 0.00000001); // 0.00000001 is used to avoid division by 0
let rsi = 100.0 - (100.0 / (1.0 + rs));

View File

@ -4,10 +4,10 @@
use crate::database_control::*;
use crate::value_estimation_team::indicators::rsi::RsiData;
use csv::{DeserializeRecordsIter, StringRecord};
use futures::{future::try_join_all, lock::Mutex};
use serde::Deserialize;
use sqlx::FromRow;
use std::f64::NAN;
use futures::{future::try_join_all, lock::Mutex};
use std::sync::Arc;
use tokio::{fs::*, io::AsyncWriteExt, time::*};
@ -55,7 +55,10 @@ pub async fn stoch_rsi(
let mut stoch_rsi_data_vec: Vec<StochRsiData> = Vec::new();
if stoch_rsi_length == 0 || smooth_k == 0 || smooth_d == 0 {
panic!("stoch_rsi_length or smooth_k or smooth_d can't be 0! stoch_rsi_length: {}, k:{}, d:{}", stoch_rsi_length, smooth_k, smooth_d);
panic!(
"stoch_rsi_length or smooth_k or smooth_d can't be 0! stoch_rsi_length: {}, k:{}, d:{}",
stoch_rsi_length, smooth_k, smooth_d
);
}
let mut task_vec = Vec::new();
for element in input_rsi_data {
@ -70,9 +73,10 @@ pub async fn stoch_rsi(
let mut stoch_rsi_vec: Vec<RsiData> = Vec::new();
let mut stoch_rsi = RsiData::new();
if element_c.1.len() >= stoch_rsi_length &&
element_c.1.len() >= smooth_k &&
element_c.1.len() >= smooth_d {
if element_c.1.len() >= stoch_rsi_length
&& element_c.1.len() >= smooth_k
&& element_c.1.len() >= smooth_d
{
let mut read_data_vec = element_c.1;
let window_iter = read_data_vec.windows(stoch_rsi_length);