Skip to content

Commit 12ac962

Browse files
committed
_
1 parent 5f75f78 commit 12ac962

File tree

13 files changed

+92
-66
lines changed

13 files changed

+92
-66
lines changed

Cargo.lock

Lines changed: 34 additions & 9 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

discretionary_engine/src/adjust_pos.rs

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ pub(crate) async fn main(args: AdjustPosArgs, live_settings: Arc<LiveSettings>,
112112
// Get current ticker price first
113113
let symbol_raw = args.ticker.symbol.to_string();
114114
let symbol = convert_symbol_to_bybit(&symbol_raw);
115-
info!("Fetching current price for {} (converted from {})", symbol, symbol_raw);
115+
info!("Fetching current price for {symbol} (converted from {symbol_raw})");
116116

117117
let ticker_params = BybitTickersParamsBuilder::default()
118118
.category(BybitProductType::Linear)
@@ -128,7 +128,7 @@ pub(crate) async fn main(args: AdjustPosArgs, live_settings: Arc<LiveSettings>,
128128
let ticker = ticker_response.result.list.get(0).ok_or_else(|| color_eyre::eyre::eyre!("No ticker data found for {}", symbol))?;
129129

130130
let current_price: f64 = ticker.last_price.parse().context("Failed to parse price as float")?;
131-
info!("Current price: ${}", current_price);
131+
info!("Current price: ${current_price}");
132132

133133
// Fetch instrument info to get lot size filter
134134
let instruments_params = BybitInstrumentsInfoParamsBuilder::default()
@@ -156,10 +156,7 @@ pub(crate) async fn main(args: AdjustPosArgs, live_settings: Arc<LiveSettings>,
156156
let price_filter = &instrument.price_filter;
157157
let tick_size: f64 = price_filter.tick_size.parse().context("Failed to parse tickSize")?;
158158

159-
info!(
160-
"Instrument info - qtyStep: {}, tickSize: {}, minOrderQty: {}, maxOrderQty: {}",
161-
qty_step, tick_size, min_order_qty, max_order_qty
162-
);
159+
info!("Instrument info - qtyStep: {qty_step}, tickSize: {tick_size}, minOrderQty: {min_order_qty}, maxOrderQty: {max_order_qty}");
163160

164161
// Calculate quantity based on size type, extracting sign for order side
165162
let (raw_quantity, side) = match size_type {
@@ -196,7 +193,7 @@ pub(crate) async fn main(args: AdjustPosArgs, live_settings: Arc<LiveSettings>,
196193

197194
// Create InstrumentId for ticker subscription
198195
// Format: "SYMBOL.VENUE" e.g., "BTCUSDT.BYBIT"
199-
let instrument_id = InstrumentId::from(format!("{}.BYBIT", symbol).as_str());
196+
let instrument_id = InstrumentId::from(format!("{symbol}.BYBIT").as_str());
200197

201198
let filled_qty = crate::ws_chase_limit::execute_ws_chase_limit(
202199
&raw_client, api_key, api_secret, environment, &symbol, instrument_id, side, quantity, qty_step, tick_size, args.duration,
@@ -217,7 +214,7 @@ pub(crate) async fn main(args: AdjustPosArgs, live_settings: Arc<LiveSettings>,
217214
} else if qty_step >= 0.01 {
218215
format!("{:.2}", quantity)
219216
} else {
220-
format!("{}", quantity)
217+
format!("{quantity}")
221218
};
222219

223220
// Prepare order request
@@ -232,7 +229,7 @@ pub(crate) async fn main(args: AdjustPosArgs, live_settings: Arc<LiveSettings>,
232229
"reduceOnly": args.reduce,
233230
});
234231

235-
info!("Submitting market {} order for {} {}", side, quantity, symbol);
232+
info!("Submitting market {side} order for {quantity} {symbol}");
236233

237234
// Submit order
238235
let order_response = client.place_order(&order_request).await.context("Failed to place order")?;
@@ -241,7 +238,7 @@ pub(crate) async fn main(args: AdjustPosArgs, live_settings: Arc<LiveSettings>,
241238
println!("✅ Order submitted successfully!");
242239
info!("Order submitted successfully!");
243240
if let Some(order_id) = order_response.result.order_id {
244-
println!(" Order ID: {}", order_id);
241+
println!(" Order ID: {order_id}");
245242
}
246243
println!(" Quantity: {} {} (notional: ${:.2})", qty_str, symbol, actual_notional);
247244
Ok(())

discretionary_engine/src/bybit_common.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ impl BybitAmendClient {
9797
let param_str = serde_json::to_string(&params)?;
9898

9999
// Bybit signature: timestamp + api_key + recv_window + param_str
100-
let sign_str = format!("{}{}{}{}", timestamp, self.api_key, recv_window, param_str);
100+
let sign_str = format!("{timestamp}{}{recv_window}{param_str}", self.api_key);
101101

102102
let mut mac = Hmac::<Sha256>::new_from_slice(self.api_secret.as_bytes()).map_err(|e| color_eyre::eyre::eyre!("Invalid secret key: {}", e))?;
103103
mac.update(sign_str.as_bytes());
@@ -139,7 +139,7 @@ impl BybitAmendClient {
139139
let param_str = serde_json::to_string(&params)?;
140140

141141
// Bybit signature: timestamp + api_key + recv_window + param_str
142-
let sign_str = format!("{}{}{}{}", timestamp, self.api_key, recv_window, param_str);
142+
let sign_str = format!("{timestamp}{}{recv_window}{param_str}", self.api_key);
143143

144144
let mut mac = Hmac::<Sha256>::new_from_slice(self.api_secret.as_bytes()).map_err(|e| color_eyre::eyre::eyre!("Invalid secret key: {}", e))?;
145145
mac.update(sign_str.as_bytes());

discretionary_engine/src/chase_limit.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ use v_utils::{log, trades::Timeframe};
2323
/// * `symbol` - Trading symbol (Bybit format, e.g., "BTCUSDT")
2424
/// * `side` - Order side ("Buy" or "Sell")
2525
/// * `target_qty` - Total quantity to execute
26-
/// * `qty_step` - Minimum quantity increment for the instrument
2726
/// * `price_tick` - Minimum price increment for the instrument
2827
/// * `duration` - Optional duration to spread the execution over
2928
pub async fn execute_chase_limit(
@@ -32,11 +31,10 @@ pub async fn execute_chase_limit(
3231
symbol: &str,
3332
side: &str,
3433
target_qty: f64,
35-
qty_step: f64,
3634
price_tick: f64,
3735
duration: Option<Timeframe>,
3836
) -> Result<f64> {
39-
log!("Starting chase-limit execution for {} {} {}", side, target_qty, symbol);
37+
log!("Starting chase-limit execution for {side} {target_qty} {symbol}");
4038

4139
// Calculate execution parameters based on duration
4240
let (sleep_interval, end_time) = if let Some(duration_tf) = duration {
@@ -56,6 +54,7 @@ pub async fn execute_chase_limit(
5654
let mut last_order_price: Option<f64> = None;
5755
let mut iteration = 0;
5856

57+
//LOOP: very bad interface from the old implementation. Shouldn't be done this way, - will transfer to implementation through protocol primitives
5958
loop {
6059
iteration += 1;
6160

@@ -134,7 +133,7 @@ pub async fn execute_chase_limit(
134133
_ => bail!("Invalid side: {}", side),
135134
};
136135

137-
info!("[{}] Market: bid={}, ask={}, target {} limit @ {}", iteration, bid_price, ask_price, side, limit_price);
136+
info!("[{iteration}] Market: bid={bid_price}, ask={ask_price}, target {side} limit @ {limit_price}");
138137

139138
// Check if we should update the order
140139
// Only update if price changed significantly (to avoid unnecessary cancel-replace)
@@ -146,7 +145,7 @@ pub async fn execute_chase_limit(
146145
if should_update {
147146
// Cancel existing order if there is one
148147
if let Some(ref old_order_link_id) = current_order_link_id {
149-
log!("[{}] Cancelling previous order to update price", iteration);
148+
log!("[{iteration}] Cancelling previous order to update price");
150149

151150
let cancel_request = serde_json::json!({
152151
"category": "linear",
@@ -162,10 +161,10 @@ pub async fn execute_chase_limit(
162161
}
163162

164163
// Create new orderLinkId for this order
165-
let new_order_link_id = format!("{}-{}", base_order_link_id, iteration);
164+
let new_order_link_id = format!("{base_order_link_id}-{iteration}");
166165

167166
// Place new order at updated price
168-
log!("[{}] Placing {} limit order: {} @ {}", iteration, side, target_qty, limit_price);
167+
log!("[{iteration}] Placing {side} limit order: {target_qty} @ {limit_price}");
169168

170169
let order_request = serde_json::json!({
171170
"category": "linear",
@@ -183,15 +182,15 @@ pub async fn execute_chase_limit(
183182
if order_response.ret_code == 0 {
184183
current_order_link_id = Some(new_order_link_id);
185184
last_order_price = Some(limit_price);
186-
info!("[{}] Order placed successfully", iteration);
185+
info!("[{iteration}] Order placed successfully");
187186
} else if order_response.ret_code == 10001 || order_response.ret_msg.contains("post only") || order_response.ret_msg.contains("would cross") {
188-
info!("[{}] PostOnly rejected (would cross spread): {}, will retry", iteration, order_response.ret_msg);
187+
info!("[{iteration}] PostOnly rejected (would cross spread): {}, will retry", order_response.ret_msg);
189188
// Don't update last_order_price or current_order_link_id, will retry next iteration
190189
} else {
191190
log!("Order placement warning: {} (code: {})", order_response.ret_msg, order_response.ret_code);
192191
}
193192
} else {
194-
info!("[{}] Price unchanged, keeping order at {}", iteration, last_order_price.unwrap_or(0.0));
193+
info!("[{iteration}] Price unchanged, keeping order at {}", last_order_price.unwrap_or(0.0));
195194
}
196195

197196
// Sleep before next iteration
@@ -204,6 +203,6 @@ pub async fn execute_chase_limit(
204203
}
205204
}
206205

207-
log!("Chase-limit execution completed for {} {}", target_qty, symbol);
206+
log!("Chase-limit execution completed for {target_qty} {symbol}");
208207
Ok(target_qty)
209208
}

discretionary_engine/src/exchange_apis/binance/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ pub async fn signed_request<S: AsRef<str>>(http_method: reqwest::Method, endpoin
108108

109109
for attempt in 0..max_retries {
110110
let time_ms = Utc::now().timestamp_millis();
111-
params.insert("timestamp", format!("{}", time_ms));
111+
params.insert("timestamp", format!("{time_ms}"));
112112

113113
let query_string = serde_urlencoded::to_string(&params)?;
114114

@@ -117,7 +117,7 @@ pub async fn signed_request<S: AsRef<str>>(http_method: reqwest::Method, endpoin
117117
let mac_bytes = mac.finalize().into_bytes();
118118
let signature = hex::encode(mac_bytes);
119119

120-
let url = format!("{}?{}&signature={}", endpoint_str, query_string, signature);
120+
let url = format!("{endpoint_str}?{query_string}&signature={signature}");
121121
let r = client.request(http_method.clone(), &url).send().await?;
122122

123123
if r.status().is_success() {

discretionary_engine/src/main.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ async fn main() -> Result<()> {
131131
let live_settings = match LiveSettings::new(cli.settings, Duration::from_secs(5)) {
132132
Ok(ls) => Arc::new(ls),
133133
Err(e) => {
134-
eprintln!("Loading config failed: {}", e);
134+
eprintln!("Loading config failed: {e}");
135135
std::process::exit(1);
136136
}
137137
};
@@ -199,12 +199,12 @@ async fn command_new(position_args: PositionArgs, live_settings: Arc<LiveSetting
199199
let balance = match Exchanges::compile_total_balance(exchanges_arc.clone(), live_settings.clone()).await {
200200
Ok(b) => b,
201201
Err(e) => {
202-
eprintln!("Failed to get balance: {}", e);
202+
eprintln!("Failed to get balance: {e}");
203203
std::process::exit(1);
204204
}
205205
};
206-
info!("Total balance: {}", balance);
207-
println!("Current total available balance: {}", balance);
206+
info!("Total balance: {balance}");
207+
println!("Current total available balance: {balance}");
208208

209209
let (side, target_size) = match position_args.size_usdt {
210210
s if s > 0.0 => (Side::Buy, s),

0 commit comments

Comments
 (0)