1use crate::client::IndodaxClient;
2use crate::commands::helpers;
3use crate::config::IndodaxConfig;
4use crate::errors::IndodaxError;
5use crate::output::CommandOutput;
6use futures_util::future::join_all;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9
10pub const DEFAULT_BALANCE_IDR: f64 = 100_000_000.0;
11pub const DEFAULT_BALANCE_BTC: f64 = 1.0;
12const TAKER_FEE: f64 = 0.0026; const BALANCE_EPSILON: f64 = 1e-8;
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct PaperOrder {
17 pub id: u64,
18 pub pair: String,
19 pub side: String,
20 pub price: f64,
21 pub amount: f64,
22 pub remaining: f64,
23 pub order_type: String,
24 pub status: String,
25 pub created_at: u64,
26 #[serde(default)]
27 pub fees_paid: f64,
28 #[serde(default)]
29 pub filled_price: f64,
30 #[serde(default)]
31 pub total_spent: f64,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct PaperState {
36 pub balances: HashMap<String, f64>,
37 pub orders: Vec<PaperOrder>,
38 pub next_order_id: u64,
39 pub trade_count: u64,
40 #[serde(default)]
41 pub total_fees_paid: f64,
42 #[serde(default)]
43 pub initial_balances: Option<HashMap<String, f64>>,
44}
45
46impl Default for PaperState {
47 fn default() -> Self {
48 let mut balances = HashMap::new();
49 balances.insert("idr".into(), DEFAULT_BALANCE_IDR);
50 balances.insert("btc".into(), DEFAULT_BALANCE_BTC);
51 Self {
52 initial_balances: Some(balances.clone()),
53 balances,
54 orders: Vec::new(),
55 next_order_id: 1,
56 trade_count: 0,
57 total_fees_paid: 0.0,
58 }
59 }
60}
61
62impl PaperState {
63 pub fn initial_balance(&self, currency: &str) -> f64 {
64 self.initial_balances
65 .as_ref()
66 .and_then(|b| b.get(currency).copied())
67 .unwrap_or(0.0)
68 }
69}
70
71impl PaperState {
72 pub fn load(config: &IndodaxConfig) -> Self {
73 let mut result: Option<PaperState> = config
74 .paper_balances
75 .as_ref()
76 .and_then(|v| serde_json::from_value(v.clone()).ok());
77 if config.paper_balances.is_some() && result.is_none() {
78 eprintln!("[PAPER] Warning: Failed to deserialize saved paper state, resetting to defaults");
79 }
80 if let Some(ref mut state) = result {
81 if state.initial_balances.is_none() {
82 eprintln!("[PAPER] Warning: Saved state predates balance tracking. Snapshotting current balances as initial (P&L will reflect only future changes).");
83 state.initial_balances = Some(state.balances.clone());
84 }
85 }
86 result.unwrap_or_default()
87 }
88
89 pub fn save(&self, config: &mut IndodaxConfig) -> Result<(), IndodaxError> {
90 config.paper_balances = Some(serde_json::to_value(self).map_err(|e| IndodaxError::Other(e.to_string()))?);
91 config.save().map_err(|e| IndodaxError::Other(e.to_string()))?;
92 Ok(())
93 }
94}
95
96#[derive(Debug, clap::Subcommand)]
97pub enum PaperCommand {
98 #[command(name = "init", about = "Initialize paper trading with custom or default balances")]
99 Init {
100 #[arg(long, help = "Initial IDR balance (default: 100000000)")]
101 idr: Option<f64>,
102 #[arg(long, help = "Initial BTC balance (default: 1.0)")]
103 btc: Option<f64>,
104 },
105
106 #[command(name = "reset", about = "Reset paper trading state")]
107 Reset,
108
109 #[command(name = "topup", about = "Add balance to a currency")]
110 Topup {
111 #[arg(short = 'c', long, help = "Currency to topup (e.g. idr, btc)")]
112 currency: String,
113 #[arg(short = 'a', long, help = "Amount to add")]
114 amount: f64,
115 },
116
117 #[command(name = "balance", about = "Show paper trading balances")]
118 Balance,
119
120 #[command(name = "buy", about = "Place a simulated buy order")]
121 Buy {
122 #[arg(short = 'p', long, help = "Trading pair (e.g. btc_idr)")]
123 pair: String,
124 #[arg(short = 'i', long, help = "The total IDR amount to spend.")]
125 idr: Option<f64>,
126 #[arg(short = 'a', long, help = "Amount in base currency (e.g. BTC) (alternative to --idr)")]
127 amount: Option<f64>,
128 #[arg(short = 'r', long, help = "Limit price. If omitted, a market order will be placed.")]
129 price: Option<f64>,
130 },
131
132 #[command(name = "sell", about = "Place a simulated sell order")]
133 Sell {
134 #[arg(short = 'p', long, help = "Trading pair (e.g. btc_idr)")]
135 pair: String,
136 #[arg(short = 'a', long, help = "Amount in base currency (e.g. BTC)")]
137 amount: f64,
138 #[arg(short = 'r', long, help = "Limit price. If omitted, a market order will be placed.")]
139 price: Option<f64>,
140 },
141
142 #[command(name = "orders", about = "List open paper orders (use history for all orders)")]
143 Orders {
144 #[arg(short = 'p', long, help = "Filter by trading pair (e.g. btc_idr)")]
145 pair: Option<String>,
146 #[arg(long, help = "Sort by field: id, pair, side, price, amount, remaining, status")]
147 sort_by: Option<String>,
148 #[arg(long, default_value = "asc", help = "Sort order: asc or desc")]
149 sort_order: Option<String>,
150 },
151
152 #[command(name = "cancel", about = "Cancel a paper order")]
153 Cancel {
154 #[arg(short = 'i', long, help = "Order ID to cancel")]
155 order_id: u64,
156 },
157
158 #[command(name = "cancel-all", about = "Cancel all paper orders")]
159 CancelAll,
160
161 #[command(name = "fill", about = "Fill an open paper order")]
162 Fill {
163 #[arg(short = 'i', long, help = "Order ID to fill (required unless --all is set)")]
164 order_id: Option<u64>,
165 #[arg(short = 'r', long, help = "Fill price (defaults to order price)")]
166 price: Option<f64>,
167 #[arg(short = 'a', long, help = "Fill all open orders at once")]
168 all: bool,
169 #[arg(short = 'f', long, help = "Fetch live prices from Indodax to fill matching orders")]
170 fetch: bool,
171 },
172
173 #[command(name = "history", about = "Show paper trading history")]
174 History {
175 #[arg(long, help = "Sort by field: id, pair, side, price, amount, status")]
176 sort_by: Option<String>,
177 #[arg(long, default_value = "desc", help = "Sort order: asc or desc (default: newest first)")]
178 sort_order: Option<String>,
179 },
180
181 #[command(name = "check-fills", about = "Auto-fill open orders when market conditions match")]
182 CheckFills {
183 #[arg(short = 'p', long, help = "JSON object of current market prices, e.g. '{\"btc_idr\": 100000000}'")]
184 prices: Option<String>,
185 #[arg(long, help = "Auto-fetch current market prices from Indodax API for relevant pairs")]
186 fetch: bool,
187 },
188
189 #[command(name = "status", about = "Show paper trading status summary")]
190 Status,
191
192 #[command(name = "watch", about = "Automatically watch market and fill matching orders in real-time")]
193 Watch {
194 #[arg(short, long, default_value = "30", help = "Polling interval in seconds")]
195 interval: u64,
196 #[arg(long, help = "Stop after first fill")]
197 once: bool,
198 },
199}
200
201pub async fn execute(
202 client: &IndodaxClient,
203 config: &mut IndodaxConfig,
204 cmd: &PaperCommand,
205) -> Result<CommandOutput, IndodaxError> {
206 let mut state = PaperState::load(config);
207 let result = dispatch_paper(client, &mut state, config, cmd).await;
208 state.save(config)?;
209 result
210}
211
212async fn dispatch_paper(
213 client: &IndodaxClient,
214 state: &mut PaperState,
215 config: &mut IndodaxConfig,
216 cmd: &PaperCommand,
217) -> Result<CommandOutput, IndodaxError> {
218 match cmd {
219 PaperCommand::Init { idr, btc } => paper_init(state, *idr, *btc),
220 PaperCommand::Reset => paper_reset(state),
221 PaperCommand::Topup { currency, amount } => paper_topup(state, currency, *amount),
222 PaperCommand::Balance => paper_balance(state),
223 PaperCommand::Buy { pair, idr, amount, price } => {
224 let pair = helpers::normalize_pair(pair);
225 if let Some(idr_val) = idr {
226 place_paper_order_idr(state, &pair, "buy", *idr_val, *price)
227 } else if let Some(amt) = amount {
228 place_paper_order(state, &pair, "buy", *price, *amt)
229 } else {
230 Err(IndodaxError::Other("Either --idr or --amount must be specified".to_string()))
231 }
232 }
233 PaperCommand::Sell { pair, price, amount } => {
234 let pair = helpers::normalize_pair(pair);
235 place_paper_order(state, &pair, "sell", *price, *amount)
236 }
237 PaperCommand::Orders { pair, sort_by, sort_order } => {
238 let pair = pair.as_ref().map(|p| helpers::normalize_pair(p));
239 paper_orders(state, pair.as_deref(), sort_by.as_deref(), sort_order.as_deref())
240 }
241 PaperCommand::Cancel { order_id } => paper_cancel(state, *order_id),
242 PaperCommand::CancelAll => paper_cancel_all(state),
243 PaperCommand::Fill { order_id, price, all, fetch } => paper_fill(state, *order_id, *price, *all, Some(client), *fetch).await,
244 PaperCommand::CheckFills { prices, fetch } => paper_check_fills(client, state, prices.as_deref(), *fetch).await,
245 PaperCommand::History { sort_by, sort_order } => {
246 paper_history(state, sort_by.as_deref(), sort_order.as_deref())
247 }
248 PaperCommand::Status => paper_status(state),
249 PaperCommand::Watch { interval, once } => paper_watch(client, config, *interval, *once).await,
250 }
251}
252
253pub fn init_paper_state(idr: Option<f64>, btc: Option<f64>) -> PaperState {
254 let mut balances = HashMap::new();
255 balances.insert("idr".into(), idr.unwrap_or(DEFAULT_BALANCE_IDR));
256 balances.insert("btc".into(), btc.unwrap_or(DEFAULT_BALANCE_BTC));
257 let initial = balances.clone();
258 PaperState {
259 balances,
260 orders: Vec::new(),
261 next_order_id: 1,
262 trade_count: 0,
263 total_fees_paid: 0.0,
264 initial_balances: Some(initial),
265 }
266}
267
268fn paper_init(state: &mut PaperState, idr: Option<f64>, btc: Option<f64>) -> Result<CommandOutput, IndodaxError> {
269 *state = init_paper_state(idr, btc);
270 let data = serde_json::json!({
271 "mode": "paper",
272 "status": "initialized",
273 "balances": state.balances,
274 });
275 Ok(CommandOutput::json(data).with_addendum("[PAPER] Trading initialized with virtual balances"))
276}
277
278fn paper_reset(state: &mut PaperState) -> Result<CommandOutput, IndodaxError> {
279 *state = PaperState::default();
280 let data = serde_json::json!({
281 "mode": "paper",
282 "status": "reset"
283 });
284 Ok(CommandOutput::json(data).with_addendum("[PAPER] Trading state reset"))
285}
286
287fn paper_topup(state: &mut PaperState, currency: &str, amount: f64) -> Result<CommandOutput, IndodaxError> {
288 if amount <= 0.0 {
289 return Err(IndodaxError::Other(
290 format!("[PAPER] Amount must be positive, got {}", amount)
291 ));
292 }
293 let balance_val = {
294 let balance = state.balances.entry(currency.to_lowercase()).or_insert(0.0);
295 *balance += amount;
296 *balance
297 };
298 round_balance(&mut state.balances, ¤cy.to_lowercase());
299 let current_balance = *state.balances.get(¤cy.to_lowercase()).unwrap_or(&balance_val);
300 let data = serde_json::json!({
301 "mode": "paper",
302 "currency": currency.to_uppercase(),
303 "amount_added": amount,
304 "new_balance": current_balance,
305 });
306 Ok(CommandOutput::json(data).with_addendum(format!(
307 "[PAPER] Added {} to {} balance. New balance: {}",
308 format_balance(currency, amount),
309 currency.to_uppercase(),
310 format_balance(currency, current_balance)
311 )))
312}
313
314fn is_fiat_or_stable(currency: &str) -> bool {
315 match currency.to_lowercase().as_str() {
316 "idr" | "usdt" | "usdc" | "dai" | "busd" | "pax" | "usde" | "gusd" | "tusd" => true,
317 _ => false,
318 }
319}
320
321pub fn format_balance(currency: &str, value: f64) -> String {
322 if is_fiat_or_stable(currency) {
323 format!("{:.2}", value)
324 } else {
325 format!("{:.8}", value)
326 }
327}
328
329fn paper_balance(state: &PaperState) -> Result<CommandOutput, IndodaxError> {
330 let headers = vec!["Currency".into(), "Balance".into()];
331 let mut rows_with_balance: Vec<(f64, Vec<String>)> = state
332 .balances
333 .iter()
334 .map(|(k, v)| (*v, vec![k.to_uppercase(), format_balance(k, *v)]))
335 .collect();
336 rows_with_balance.sort_by(|a, b| {
337 b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)
338 });
339 let rows: Vec<Vec<String>> = rows_with_balance.into_iter().map(|(_, r)| r).collect();
340
341 let data = paper_balance_value(state);
342 let balance_count = state.balances.len();
343 Ok(CommandOutput::new(data, headers, rows)
344 .with_addendum(format!("[PAPER] {} balance(s) tracked", balance_count)))
345}
346
347pub fn place_paper_order(
348 state: &mut PaperState,
349 pair: &str,
350 side: &str,
351 price: Option<f64>,
352 amount: f64,
353) -> Result<CommandOutput, IndodaxError> {
354 if amount <= 0.0 {
355 return Err(IndodaxError::Other(
356 format!("[PAPER] Amount must be positive, got {}", amount)
357 ));
358 }
359 let is_market = price.is_none();
360 let order_price = price.unwrap_or(0.0);
361 if !is_market && order_price <= 0.0 {
362 return Err(IndodaxError::Other(
363 format!("[PAPER] Price must be positive, got {}", order_price)
364 ));
365 }
366 let base = pair.split('_').next().unwrap_or(pair);
367 let quote = pair.split('_').next_back().unwrap_or("idr");
368 let total_cost = order_price * amount;
369
370 if side == "buy" {
371 if is_market {
372 let quote_balance = state.balances.entry(quote.to_string()).or_insert(0.0);
373 if *quote_balance <= 0.0 {
374 return Err(IndodaxError::Other(
375 format!("[PAPER] Insufficient {} balance for market buy. Need positive balance, have {}",
376 quote.to_uppercase(), format_balance(quote, *quote_balance))
377 ));
378 }
379 } else {
380 let quote_balance = state.balances.entry(quote.to_string()).or_insert(0.0);
381 if *quote_balance + BALANCE_EPSILON < total_cost {
382 return Err(IndodaxError::Other(
383 format!("[PAPER] Insufficient {} balance. Need {}, have {}",
384 quote.to_uppercase(), format_balance(quote, total_cost), format_balance(quote, *quote_balance))
385 ));
386 }
387 *quote_balance -= total_cost;
388 round_balance(&mut state.balances, quote);
389 }
390 } else {
391 let base_balance = state.balances.entry(base.to_string()).or_insert(0.0);
392 if *base_balance + BALANCE_EPSILON < amount {
393 return Err(IndodaxError::Other(
394 format!("[PAPER] Insufficient {} balance. Need {}, have {}",
395 base.to_uppercase(), format_balance(base, amount), format_balance(base, *base_balance))
396 ));
397 }
398 *base_balance -= amount;
399 }
400
401 let order_id = state.next_order_id;
402 state.next_order_id += 1;
403
404 let now = std::time::SystemTime::now()
405 .duration_since(std::time::UNIX_EPOCH)
406 .unwrap_or_default()
407 .as_millis() as u64;
408
409 state.orders.push(PaperOrder {
410 id: order_id,
411 pair: pair.to_string(),
412 side: side.to_string(),
413 price: order_price,
414 amount,
415 remaining: amount,
416 order_type: if is_market { "market".into() } else { "limit".into() },
417 status: "open".into(),
418 created_at: now,
419 fees_paid: 0.0,
420 filled_price: 0.0,
421 total_spent: if side == "buy" && !is_market { total_cost } else { 0.0 },
422 });
423
424 state.trade_count += 1;
425
426 let price_display = if is_market { "market".to_string() } else { order_price.to_string() };
427 let data = serde_json::json!({
428 "mode": "paper",
429 "order_id": order_id,
430 "pair": pair,
431 "side": side,
432 "price": order_price,
433 "amount": amount,
434 "order_type": if is_market { "market" } else { "limit" },
435 "status": "open",
436 });
437
438 let headers = vec!["Field".into(), "Value".into()];
439 let rows = vec![
440 vec!["Order ID".into(), order_id.to_string()],
441 vec!["Pair".into(), pair.to_string()],
442 vec!["Side".into(), side.to_string()],
443 vec!["Price".into(), price_display.clone()],
444 vec!["Amount".into(), amount.to_string()],
445 vec!["Type".into(), if is_market { "market".into() } else { "limit".into() }],
446 vec!["Status".into(), "open".into()],
447 ];
448
449 Ok(CommandOutput::new(data, headers, rows)
450 .with_addendum(format!("[PAPER] {} {} {} @ {} — open", side, amount, pair, price_display)))
451}
452
453pub fn place_paper_order_idr(
454 state: &mut PaperState,
455 pair: &str,
456 side: &str,
457 idr_amount: f64,
458 price: Option<f64>,
459) -> Result<CommandOutput, IndodaxError> {
460 if idr_amount <= 0.0 {
461 return Err(IndodaxError::Other(
462 format!("[PAPER] IDR amount must be positive, got {}", idr_amount)
463 ));
464 }
465 if side != "buy" {
466 return Err(IndodaxError::Other(
467 "[PAPER] --idr is only valid for buy orders".to_string()
468 ));
469 }
470 if price.is_none() {
471 return Err(IndodaxError::Other(
472 "[PAPER] Market buy via --idr requires a limit price (simulation cannot guess the fill price)".to_string()
473 ));
474 }
475 let order_price = price.unwrap_or(0.0);
476 if order_price <= 0.0 {
477 return Err(IndodaxError::Other(
478 format!("[PAPER] Price must be positive, got {}", order_price)
479 ));
480 }
481 let quote = pair.split('_').next_back().unwrap_or("idr");
482
483 let amount = {
484 let quote_balance = state.balances.entry(quote.to_string()).or_insert(0.0);
485 if *quote_balance + BALANCE_EPSILON < idr_amount {
486 return Err(IndodaxError::Other(
487 format!("[PAPER] Insufficient {} balance. Need {}, have {}",
488 quote.to_uppercase(), format_balance(quote, idr_amount), format_balance(quote, *quote_balance))
489 ));
490 }
491 *quote_balance -= idr_amount;
492 round_balance(&mut state.balances, quote);
493 idr_amount / order_price
494 };
495
496 let order_id = state.next_order_id;
497 state.next_order_id += 1;
498
499 let now = std::time::SystemTime::now()
500 .duration_since(std::time::UNIX_EPOCH)
501 .unwrap_or_default()
502 .as_millis() as u64;
503
504 state.orders.push(PaperOrder {
505 id: order_id,
506 pair: pair.to_string(),
507 side: side.to_string(),
508 price: order_price,
509 amount,
510 remaining: amount,
511 order_type: "limit".into(),
512 status: "open".into(),
513 created_at: now,
514 fees_paid: 0.0,
515 filled_price: 0.0,
516 total_spent: idr_amount,
517 });
518
519 state.trade_count += 1;
520
521 let price_display = order_price.to_string();
522 let data = serde_json::json!({
523 "mode": "paper",
524 "order_id": order_id,
525 "pair": pair,
526 "side": side,
527 "price": order_price,
528 "amount": amount,
529 "order_type": "limit",
530 "status": "open",
531 });
532
533 let headers = vec!["Field".into(), "Value".into()];
534 let rows = vec![
535 vec!["Order ID".into(), order_id.to_string()],
536 vec!["Pair".into(), pair.to_string()],
537 vec!["Side".into(), side.to_string()],
538 vec!["Price".into(), price_display.clone()],
539 vec!["Amount".into(), format!("{:.8}", amount)],
540 vec!["IDR Spent".into(), format!("{:.2}", idr_amount)],
541 vec!["Type".into(), "limit".into()],
542 vec!["Status".into(), "open".into()],
543 ];
544
545 let base = pair.split('_').next().unwrap_or("btc");
546 Ok(CommandOutput::new(data, headers, rows)
547 .with_addendum(format!("[PAPER] buy {} {} for {} IDR @ {} — open", amount, base, idr_amount, price_display)))
548}
549
550fn round_balance(balances: &mut HashMap<String, f64>, currency: &str) {
551 if let Some(balance) = balances.get_mut(currency) {
552 if is_fiat_or_stable(currency) {
553 *balance = (*balance * 100.0).round() / 100.0;
554 } else {
555 *balance = (*balance * 100_000_000.0).round() / 100_000_000.0;
556 }
557 }
558}
559
560fn execute_fill(
561 state: &mut PaperState,
562 order_id: u64,
563 base: &str,
564 quote: &str,
565 side: &str,
566 price: f64,
567 amount: f64,
568) -> Result<(), IndodaxError> {
569 let total = price * amount;
570 let fee = total * TAKER_FEE;
571 if side == "buy" {
572 let quote_balance = state.balances.entry(quote.to_string()).or_insert(0.0);
573 if *quote_balance < fee {
574 return Err(IndodaxError::Other(format!(
575 "[PAPER] Insufficient {} balance to pay fee of {:.2}. Need {:.2}, have {:.2}",
576 quote.to_uppercase(), fee, fee, *quote_balance
577 )));
578 }
579 *quote_balance -= fee;
580 round_balance(&mut state.balances, quote);
581 let base_balance = state.balances.entry(base.to_string()).or_insert(0.0);
582 *base_balance += amount;
583 } else {
584 let quote_balance = state.balances.entry(quote.to_string()).or_insert(0.0);
585 *quote_balance += total - fee;
586 round_balance(&mut state.balances, quote);
587 }
588
589 if let Some(order) = state.orders.iter_mut().find(|o| o.id == order_id) {
590 order.remaining = 0.0;
591 order.status = "filled".to_string();
592 order.fees_paid = fee;
593 order.filled_price = price;
594 }
595 state.total_fees_paid += fee;
596 Ok(())
597}
598
599fn sort_paper_orders(orders: &mut Vec<&PaperOrder>, sort_by: Option<&str>, sort_order: Option<&str>) {
600 let desc = sort_order.map(|o| o == "desc" || o == "d").unwrap_or(false);
601 let by = sort_by.unwrap_or("id");
602 orders.sort_by(|a, b| {
603 let cmp = match by {
604 "id" => a.id.cmp(&b.id),
605 "pair" => a.pair.cmp(&b.pair),
606 "side" => a.side.cmp(&b.side),
607 "price" => a.price.partial_cmp(&b.price).unwrap_or(std::cmp::Ordering::Equal),
608 "amount" => a.amount.partial_cmp(&b.amount).unwrap_or(std::cmp::Ordering::Equal),
609 "remaining" => a.remaining.partial_cmp(&b.remaining).unwrap_or(std::cmp::Ordering::Equal),
610 "status" => a.status.cmp(&b.status),
611 _ => a.id.cmp(&b.id),
612 };
613 if desc { cmp.reverse() } else { cmp }
614 });
615}
616
617fn paper_orders(state: &PaperState, filter_pair: Option<&str>, sort_by: Option<&str>, sort_order: Option<&str>) -> Result<CommandOutput, IndodaxError> {
618 let mut filtered: Vec<&PaperOrder> = state
619 .orders
620 .iter()
621 .filter(|o| o.status == "open")
622 .filter(|o| filter_pair.is_none_or(|p| o.pair == p))
623 .collect();
624
625 sort_paper_orders(&mut filtered, sort_by, sort_order);
626
627 let headers = vec![
628 "Order ID".into(), "Pair".into(), "Side".into(), "Price".into(),
629 "Amount".into(), "Remaining".into(), "Status".into(),
630 ];
631 let rows: Vec<Vec<String>> = filtered
632 .iter()
633 .map(|o| {
634 vec![
635 o.id.to_string(),
636 o.pair.clone(),
637 o.side.clone(),
638 o.price.to_string(),
639 o.amount.to_string(),
640 o.remaining.to_string(),
641 o.status.clone(),
642 ]
643 })
644 .collect();
645
646 let data = serde_json::json!({
647 "mode": "paper",
648 "orders": filtered,
649 "count": filtered.len(),
650 });
651
652 let msg = match filter_pair {
653 Some(p) => format!("[PAPER] {} orders for {}", filtered.len(), p),
654 None => format!("[PAPER] {} orders", filtered.len()),
655 };
656
657 Ok(CommandOutput::new(data, headers, rows).with_addendum(msg))
658}
659
660fn paper_cancel(state: &mut PaperState, order_id: u64) -> Result<CommandOutput, IndodaxError> {
661 refund_and_cancel(state, order_id)?;
662
663 let data = serde_json::json!({
664 "mode": "paper",
665 "order_id": order_id,
666 "status": "cancelled"
667 });
668 Ok(CommandOutput::json(data).with_addendum(format!("[PAPER] Order {} cancelled", order_id)))
669}
670
671fn paper_cancel_all(state: &mut PaperState) -> Result<CommandOutput, IndodaxError> {
672 let (count, failures) = cancel_all_paper_orders(state);
673
674 let mut data = serde_json::json!({
675 "mode": "paper",
676 "cancelled_count": count,
677 "failed_count": failures.len(),
678 });
679 if !failures.is_empty() {
680 data["failures"] = serde_json::json!(failures.iter().map(|(id, e)| serde_json::json!({
681 "order_id": id,
682 "error": e,
683 })).collect::<Vec<_>>());
684 }
685
686 let addendum = if failures.is_empty() {
687 format!("[PAPER] Cancelled {} orders", count)
688 } else {
689 let reasons: Vec<String> = failures.iter().map(|(id, e)| format!("{}: {}", id, e)).collect();
690 format!("[PAPER] Cancelled {} orders, {} failed: {}", count, failures.len(), reasons.join("; "))
691 };
692
693 Ok(CommandOutput::json(data).with_addendum(addendum))
694}
695
696pub async fn paper_fill(
697 state: &mut PaperState,
698 order_id: Option<u64>,
699 fill_price: Option<f64>,
700 fill_all: bool,
701 client: Option<&IndodaxClient>,
702 fetch: bool,
703) -> Result<CommandOutput, IndodaxError> {
704 let mut fetched_prices: HashMap<String, f64> = HashMap::new();
705
706 if fetch {
707 let client = client.ok_or_else(|| IndodaxError::Other("client required when fetch is true".to_string()))?;
708 let pairs_to_fetch: std::collections::HashSet<String> = if let Some(id) = order_id {
709 state.orders.iter()
710 .filter(|o| o.id == id && o.status == "open")
711 .map(|o| o.pair.clone())
712 .collect()
713 } else if fill_all {
714 state.orders.iter()
715 .filter(|o| o.status == "open")
716 .map(|o| o.pair.clone())
717 .collect()
718 } else {
719 std::collections::HashSet::new()
720 };
721
722 if !pairs_to_fetch.is_empty() {
723 eprintln!("[PAPER] Fetching live prices for {} pair(s)...", pairs_to_fetch.len());
724 let futures: Vec<_> = pairs_to_fetch.iter().map(|p| async move {
725 let ticker: serde_json::Value = client.public_get(&format!("/api/ticker/{}", p)).await?;
726 let price = ticker["ticker"]["last"].as_str()
727 .and_then(|s| s.parse::<f64>().ok())
728 .or_else(|| ticker["ticker"]["last"].as_f64())
729 .ok_or_else(|| IndodaxError::Other(format!("Failed to parse price for {}", p)))?;
730 Ok::<(String, f64), IndodaxError>((p.clone(), price))
731 }).collect();
732
733 for (pair, price) in join_all(futures).await.into_iter().flatten() {
734 fetched_prices.insert(pair, price);
735 }
736 }
737 }
738
739 if fill_all {
740 let open_ids: Vec<u64> = state.orders.iter()
741 .filter(|o| o.status == "open")
742 .map(|o| o.id)
743 .collect();
744
745 if open_ids.is_empty() {
746 return Ok(CommandOutput::json(serde_json::json!({
747 "mode": "paper",
748 "filled_count": 0,
749 })).with_addendum("[PAPER] No open orders to fill"));
750 }
751
752 let mut skipped = 0u64;
753 let mut filled = 0u64;
754 let mut errors: Vec<String> = Vec::new();
755 for id in &open_ids {
756 let order = match state.orders.iter().find(|o| o.id == *id) {
757 Some(o) => o.clone(),
758 None => { skipped += 1; continue; }
759 };
760
761 let price = fetched_prices.get(&order.pair).copied()
763 .or(fill_price)
764 .unwrap_or(order.price);
765
766 if !price.is_finite() {
767 errors.push(format!("Order {}: invalid fill price {}", id, price));
768 skipped += 1;
769 continue;
770 }
771
772 let should_fill = if fetch {
773 if let Some(&live_price) = fetched_prices.get(&order.pair) {
774 match order.side.as_str() {
775 "buy" => live_price <= order.price,
776 "sell" => live_price >= order.price,
777 _ => false,
778 }
779 } else {
780 false }
782 } else {
783 match fill_price {
784 Some(fp) => match order.side.as_str() {
785 "buy" => fp <= order.price,
786 "sell" => fp >= order.price,
787 _ => false,
788 },
789 None => true,
790 }
791 };
792
793 if !should_fill { skipped += 1; continue; }
794
795 let base = order.pair.split('_').next().unwrap_or("btc").to_string();
796 let quote = order.pair.split('_').next_back().unwrap_or("idr").to_string();
797 match execute_fill(state, *id, &base, "e, &order.side, price, order.remaining) {
798 Ok(()) => filled += 1,
799 Err(e) => {
800 errors.push(format!("Order {}: {}", id, e));
801 skipped += 1;
802 }
803 }
804 }
805
806 let data = serde_json::json!({
807 "mode": "paper",
808 "filled_count": filled,
809 "skipped_count": skipped,
810 "error_count": errors.len(),
811 "errors": errors,
812 });
813
814 let addendum = if !errors.is_empty() {
815 format!("[PAPER] Filled {} order(s), {} errors: {}", filled, errors.len(), errors.join("; "))
816 } else if skipped > 0 {
817 let skip_reason = if fill_price.is_some() {
818 " (orders not matching fill price condition)"
819 } else {
820 ""
821 };
822 format!("[PAPER] Filled {} order(s), skipped {}{}", filled, skipped, skip_reason)
823 } else {
824 format!("[PAPER] Filled {} order(s)", filled)
825 };
826
827 return Ok(CommandOutput::json(data).with_addendum(addendum));
828 }
829
830 let order_id = order_id.ok_or_else(|| IndodaxError::Other("[PAPER] Either --order-id or --all must be specified".into()))?;
831
832 let (status, side, pair, order_price, amount, remaining) = {
833 let order = state.orders.iter().find(|o| o.id == order_id)
834 .ok_or_else(|| IndodaxError::Other(format!("[PAPER] Order {} not found", order_id)))?;
835 (order.status.clone(), order.side.clone(), order.pair.clone(), order.price, order.amount, order.remaining)
836 };
837
838 if status != "open" {
839 return Err(IndodaxError::Other(format!("[PAPER] Order {} status is '{}', only open orders can be filled", order_id, status)));
840 }
841
842 let price = fetched_prices.get(&pair).copied()
844 .or(fill_price)
845 .unwrap_or(order_price);
846
847 if !price.is_finite() {
848 return Err(IndodaxError::Other(format!(
849 "[PAPER] Invalid fill price: {}. Ensure order price or explicit fill price is valid.",
850 price
851 )));
852 }
853
854 if fetch {
855 if let Some(&live_price) = fetched_prices.get(&pair) {
856 let should_fill = match side.as_str() {
857 "buy" => live_price <= order_price,
858 "sell" => live_price >= order_price,
859 _ => false,
860 };
861 if !should_fill {
862 return Err(IndodaxError::Other(format!(
863 "[PAPER] Live price {} does not match order condition ({} side, limit {})",
864 live_price, side, order_price
865 )));
866 }
867 } else {
868 return Err(IndodaxError::Other(format!("[PAPER] Failed to fetch live price for {}", pair)));
869 }
870 } else if let Some(fp) = fill_price {
871 let should_fill = match side.as_str() {
872 "buy" => fp <= order_price,
873 "sell" => fp >= order_price,
874 _ => false,
875 };
876 if !should_fill {
877 return Err(IndodaxError::Other(format!(
878 "[PAPER] Fill price {} does not match order condition ({} side, limit {}). Use --all to skip non-matching orders.",
879 fp, side, order_price
880 )));
881 }
882 }
883 let base = pair.split('_').next().unwrap_or("btc");
884 let quote = pair.split('_').next_back().unwrap_or("idr");
885
886 execute_fill(state, order_id, base, quote, &side, price, remaining)?;
887
888 let data = serde_json::json!({
889 "mode": "paper",
890 "order_id": order_id,
891 "pair": pair,
892 "side": side,
893 "price": price,
894 "amount": amount,
895 "status": "filled",
896 });
897
898 let headers = vec!["Field".into(), "Value".into()];
899 let rows = vec![
900 vec!["Order ID".into(), order_id.to_string()],
901 vec!["Pair".into(), pair],
902 vec!["Side".into(), side],
903 vec!["Price".into(), price.to_string()],
904 vec!["Amount".into(), amount.to_string()],
905 vec!["Total".into(), (price * amount).to_string()],
906 vec!["Status".into(), "filled".into()],
907 ];
908
909 Ok(CommandOutput::new(data, headers, rows)
910 .with_addendum(format!("[PAPER] Order {} filled at {}", order_id, price)))
911}
912
913fn paper_history(state: &PaperState, sort_by: Option<&str>, sort_order: Option<&str>) -> Result<CommandOutput, IndodaxError> {
914 let mut sorted: Vec<&PaperOrder> = state.orders.iter().collect();
915 sort_paper_orders(&mut sorted, sort_by, sort_order);
916
917 let headers = vec![
918 "Order ID".into(),
919 "Pair".into(),
920 "Side".into(),
921 "Price".into(),
922 "Amount".into(),
923 "Status".into(),
924 ];
925 let rows: Vec<Vec<String>> = sorted
926 .iter()
927 .map(|o| {
928 vec![
929 o.id.to_string(),
930 o.pair.clone(),
931 o.side.clone(),
932 o.price.to_string(),
933 o.amount.to_string(),
934 o.status.clone(),
935 ]
936 })
937 .collect();
938
939 let data = paper_history_value(state);
940 let order_count = state.orders.len();
941 Ok(CommandOutput::new(data, headers, rows)
942 .with_addendum(format!("[PAPER] {} order(s) total", order_count)))
943}
944
945fn paper_status(state: &PaperState) -> Result<CommandOutput, IndodaxError> {
946 let data = paper_status_value(state);
947 let filled_count = data["filled_count"].as_u64().unwrap_or(0);
948 let open_count = data["open_count"].as_u64().unwrap_or(0);
949 let cancelled_count = data["cancelled_count"].as_u64().unwrap_or(0);
950
951 let pnl_parts: Vec<(String, String)> = state
952 .balances
953 .iter()
954 .filter_map(|(k, v)| {
955 let init = state.initial_balance(k);
956 if init > 0.0 || *v > 0.0 {
957 let diff = *v - init;
958 Some((
959 k.to_uppercase(),
960 format!("{} ({})", format_balance(k, *v), format!("{:+.8}", diff)),
961 ))
962 } else {
963 None
964 }
965 })
966 .collect();
967
968 let headers = vec!["Metric".into(), "Value".into()];
969 let mut rows = vec![
970 vec!["Total trades".into(), state.trade_count.to_string()],
971 vec!["Orders filled".into(), filled_count.to_string()],
972 vec!["Orders open".into(), open_count.to_string()],
973 vec!["Orders cancelled".into(), cancelled_count.to_string()],
974 vec![
975 "Total fees paid".into(),
976 format!("{:.8}", state.total_fees_paid),
977 ],
978 ];
979 for (currency, bal) in &pnl_parts {
980 rows.push(vec![format!("{} balance", currency), bal.clone()]);
981 }
982
983 Ok(CommandOutput::new(data, headers, rows).with_addendum(format!(
984 "[PAPER] {} trades, {} filled, {} open, {} cancelled",
985 state.trade_count, filled_count, open_count, cancelled_count
986 )))
987}
988
989async fn paper_watch(
990 client: &IndodaxClient,
991 config: &mut IndodaxConfig,
992 interval_secs: u64,
993 once: bool,
994) -> Result<CommandOutput, IndodaxError> {
995 use tokio::time::{sleep, Duration};
996
997 eprintln!("[PAPER] Monitoring market for open orders (interval: {}s)...", interval_secs);
998 eprintln!("[PAPER] Press Ctrl+C to stop.");
999
1000 loop {
1001 let mut state = PaperState::load(config);
1002 let open_count = state.orders.iter().filter(|o| o.status == "open").count();
1003
1004 if open_count == 0 {
1005 eprintln!("[PAPER] No open orders. Waiting {}s...", interval_secs);
1006 sleep(Duration::from_secs(interval_secs)).await;
1007 continue;
1008 }
1009
1010 match paper_fill(&mut state, None, None, true, Some(client), true).await {
1011 Ok(output) => {
1012 let data = &output.data;
1013 let filled = data["filled_count"].as_u64().unwrap_or(0);
1014
1015 if filled > 0 {
1016 eprintln!("{}", output.addendum.as_deref().unwrap_or("[PAPER] Orders filled"));
1017 state.save(config)?;
1018 if once {
1019 return Ok(output);
1020 }
1021 }
1022 }
1023 Err(e) => {
1024 eprintln!("[PAPER] Error during auto-fill: {}", e);
1025 }
1026 }
1027
1028 sleep(Duration::from_secs(interval_secs)).await;
1029 }
1030}
1031
1032async fn fetch_market_prices(
1033client: &IndodaxClient, state: &PaperState) -> Result<HashMap<String, f64>, IndodaxError> {
1034 let pairs: std::collections::BTreeSet<String> = state.orders.iter()
1035 .filter(|o| o.status == "open")
1036 .map(|o| o.pair.clone())
1037 .collect();
1038
1039 if pairs.is_empty() {
1040 return Ok(HashMap::new());
1041 }
1042
1043 let tasks: Vec<_> = pairs.iter().map(|pair| {
1044 let pair = pair.clone();
1045 let path = format!("/api/ticker/{}", pair);
1046 async move {
1047 match client.public_get::<serde_json::Value>(&path).await {
1048 Ok(data) => {
1049 if let Some(ticker) = data.get("ticker") {
1050 let last = ticker.get("last")
1051 .and_then(|v| v.as_str())
1052 .and_then(|s| s.parse::<f64>().ok())
1053 .or_else(|| ticker.get("last").and_then(|v| v.as_f64()));
1054 last.map(|price| (pair, price))
1055 } else {
1056 None
1057 }
1058 }
1059 Err(e) => {
1060 eprintln!("[PAPER] Warning: Failed to fetch price for {}: {}", pair, e);
1061 None
1062 }
1063 }
1064 }
1065 }).collect();
1066
1067 let results = join_all(tasks).await;
1068 let mut prices = HashMap::new();
1069 for result in results.into_iter().flatten() {
1070 prices.insert(result.0, result.1);
1071 }
1072 Ok(prices)
1073}
1074
1075pub async fn paper_check_fills(client: &IndodaxClient, state: &mut PaperState, prices: Option<&str>, fetch: bool) -> Result<CommandOutput, IndodaxError> {
1076 let market_prices: HashMap<String, f64> = if fetch {
1077 fetch_market_prices(client, state).await?
1078 } else if let Some(p) = prices {
1079 serde_json::from_str(p)
1080 .map_err(|e| IndodaxError::Other(format!("[PAPER] Invalid prices JSON: {}", e)))?
1081 } else {
1082 return Err(IndodaxError::Other("[PAPER] Either --prices or --fetch must be specified".into()));
1083 };
1084
1085 let market_prices: HashMap<String, f64> = market_prices
1087 .into_iter()
1088 .map(|(k, v)| (helpers::normalize_pair(&k), v))
1089 .collect();
1090
1091 let mut filled_ids: Vec<u64> = Vec::new();
1092 let mut errors: Vec<String> = Vec::new();
1093
1094 let open_ids: Vec<(u64, String, String, f64, f64)> = state.orders.iter()
1095 .filter(|o| o.status == "open")
1096 .map(|o| (o.id, o.pair.clone(), o.side.clone(), o.price, o.remaining))
1097 .collect();
1098
1099 for (order_id, pair, side, order_price, remaining) in &open_ids {
1100 let current_price = match market_prices.get(pair) {
1101 Some(p) => *p,
1102 None => continue,
1103 };
1104
1105 let should_fill = match side.as_str() {
1106 "buy" => current_price <= *order_price,
1107 "sell" => current_price >= *order_price,
1108 _ => false,
1109 };
1110
1111 if should_fill {
1112 let base = pair.split('_').next().unwrap_or("btc");
1113 let quote = pair.split('_').next_back().unwrap_or("idr");
1114 match execute_fill(state, *order_id, base, quote, side, current_price, *remaining) {
1115 Ok(()) => filled_ids.push(*order_id),
1116 Err(e) => errors.push(format!("Order {}: {}", order_id, e)),
1117 }
1118 }
1119 }
1120
1121 let data = serde_json::json!({
1122 "mode": "paper",
1123 "filled_count": filled_ids.len(),
1124 "filled_ids": filled_ids,
1125 "error_count": errors.len(),
1126 "errors": errors,
1127 });
1128
1129 let msg = if !errors.is_empty() {
1130 format!("[PAPER] Filled {} order(s) with {} error(s): {}",
1131 filled_ids.len(), errors.len(), errors.join("; "))
1132 } else if filled_ids.is_empty() {
1133 "[PAPER] No orders matched market conditions".to_string()
1134 } else {
1135 format!("[PAPER] Filled {} order(s): {}",
1136 filled_ids.len(),
1137 filled_ids.iter().map(|id| id.to_string()).collect::<Vec<_>>().join(", "))
1138 };
1139
1140 Ok(CommandOutput::json(data).with_addendum(msg))
1141}
1142
1143pub fn paper_balance_value(state: &PaperState) -> serde_json::Value {
1148 let rounded: std::collections::HashMap<String, f64> = state.balances.iter()
1149 .map(|(k, v)| {
1150 let val = match k.as_str() {
1151 "idr" | "usdt" | "usdc" => (*v * 100.0).round() / 100.0,
1152 _ => (*v * 100_000_000.0).round() / 100_000_000.0,
1153 };
1154 (k.clone(), val)
1155 })
1156 .collect();
1157 serde_json::json!({
1158 "mode": "paper",
1159 "balances": rounded,
1160 })
1161}
1162
1163pub fn paper_orders_value(state: &PaperState) -> serde_json::Value {
1164 let open_orders: Vec<&PaperOrder> = state
1165 .orders
1166 .iter()
1167 .filter(|o| o.status == "open")
1168 .collect();
1169 let count = open_orders.len();
1170 let orders: Vec<serde_json::Value> = open_orders
1171 .iter()
1172 .map(|o| serde_json::json!({
1173 "id": o.id,
1174 "pair": o.pair,
1175 "side": o.side,
1176 "price": o.price,
1177 "amount": o.amount,
1178 "remaining": o.remaining,
1179 "status": o.status,
1180 }))
1181 .collect();
1182 serde_json::json!({
1183 "mode": "paper",
1184 "count": count,
1185 "orders": orders,
1186 })
1187}
1188
1189pub fn paper_history_value(state: &PaperState) -> serde_json::Value {
1190 serde_json::json!({
1191 "mode": "paper",
1192 "orders": state.orders,
1193 "count": state.orders.len(),
1194 })
1195}
1196
1197pub fn paper_status_value(state: &PaperState) -> serde_json::Value {
1198 let filled = state.orders.iter().filter(|o| o.status == "filled").count();
1199 let open = state.orders.iter().filter(|o| o.status == "open").count();
1200 let cancelled = state.orders.iter().filter(|o| o.status == "cancelled").count();
1201 let pnl: std::collections::HashMap<String, serde_json::Value> = state
1202 .balances
1203 .iter()
1204 .filter_map(|(k, v)| {
1205 let init = state.initial_balance(k);
1206 if init > 0.0 || *v > 0.0 {
1207 Some((k.to_uppercase(), serde_json::json!({
1208 "current": v,
1209 "initial": init,
1210 "diff": v - init,
1211 })))
1212 } else {
1213 None
1214 }
1215 })
1216 .collect();
1217 serde_json::json!({
1218 "mode": "paper",
1219 "trade_count": state.trade_count,
1220 "filled_count": filled,
1221 "open_count": open,
1222 "cancelled_count": cancelled,
1223 "total_fees_paid": state.total_fees_paid,
1224 "balances": state.balances,
1225 "initial_balances": state.initial_balances,
1226 "pnl": pnl,
1227 })
1228}
1229
1230pub fn cancel_paper_order(state: &mut PaperState, order_id: u64) -> Result<(), IndodaxError> {
1236 refund_and_cancel(state, order_id)
1237}
1238
1239pub fn cancel_all_paper_orders(state: &mut PaperState) -> (usize, Vec<(u64, String)>) {
1242 let active_ids: Vec<u64> = state
1243 .orders
1244 .iter()
1245 .filter(|o| o.status == "open")
1246 .map(|o| o.id)
1247 .collect();
1248
1249 let mut success_count = 0usize;
1250 let mut failures = Vec::new();
1251 for id in &active_ids {
1252 match refund_and_cancel(state, *id) {
1253 Ok(()) => success_count += 1,
1254 Err(e) => failures.push((*id, e.to_string())),
1255 }
1256 }
1257 (success_count, failures)
1258}
1259
1260fn refund_and_cancel(state: &mut PaperState, order_id: u64) -> Result<(), IndodaxError> {
1261 let order = state.orders.iter().find(|o| o.id == order_id)
1262 .ok_or_else(|| IndodaxError::Other(format!("[PAPER] Order {} not found", order_id)))?;
1263
1264 if order.status == "filled" || order.status == "cancelled" {
1265 return Err(IndodaxError::Other(format!("[PAPER] Order {} already {}", order_id, order.status)));
1266 }
1267
1268 let base = order.pair.split('_').next().unwrap_or("btc");
1269 let quote = order.pair.split('_').next_back().unwrap_or("idr");
1270 let refund = order.price * order.remaining;
1271 let remaining = order.remaining;
1272
1273 if order.side == "buy" {
1274 *state.balances.entry(quote.to_string()).or_insert(0.0) += refund;
1275 round_balance(&mut state.balances, quote);
1276 } else {
1277 *state.balances.entry(base.to_string()).or_insert(0.0) += remaining;
1278 }
1279
1280 if let Some(order) = state.orders.iter_mut().find(|o| o.id == order_id) {
1281 order.status = "cancelled".to_string();
1282 order.remaining = 0.0;
1283 }
1284 Ok(())
1285}
1286
1287#[cfg(test)]
1288mod tests {
1289 use super::*;
1290 use crate::config::IndodaxConfig;
1291 use serde_json::json;
1292
1293 #[test]
1294 fn test_paper_state_default() {
1295 let state = PaperState::default();
1296 assert_eq!(state.balances.get("idr"), Some(&100_000_000.0));
1297 assert_eq!(state.balances.get("btc"), Some(&1.0));
1298 assert!(state.orders.is_empty());
1299 assert_eq!(state.next_order_id, 1);
1300 assert_eq!(state.trade_count, 0);
1301 assert_eq!(state.total_fees_paid, 0.0);
1302 assert!(state.initial_balances.is_some());
1303 }
1304
1305 #[test]
1306 fn test_paper_state_load_none() {
1307 let config = IndodaxConfig::default();
1308 let state = PaperState::load(&config);
1309 assert_eq!(state.balances.get("idr"), Some(&100_000_000.0));
1310 }
1311
1312 #[test]
1313 fn test_paper_state_load_some() {
1314 let mut config = IndodaxConfig::default();
1315 let state_json = json!({
1316 "balances": {"btc": 2.0, "idr": 50_000_000.0},
1317 "orders": [],
1318 "next_order_id": 5,
1319 "trade_count": 3,
1320 "total_fees_paid": 0.0,
1321 "initial_balances": {"btc": 2.0, "idr": 50_000_000.0}
1322 });
1323 config.paper_balances = Some(state_json);
1324
1325 let state = PaperState::load(&config);
1326 assert_eq!(state.balances.get("btc"), Some(&2.0));
1327 assert_eq!(state.next_order_id, 5);
1328 assert_eq!(state.trade_count, 3);
1329 assert_eq!(state.total_fees_paid, 0.0);
1330 }
1331
1332 #[test]
1333 fn test_paper_state_save() {
1334 let mut config = IndodaxConfig::default();
1335 let mut state = PaperState::default();
1336 state.balances.insert("eth".into(), 10.0);
1337 state.next_order_id = 42;
1338
1339 let result = state.save(&mut config);
1340 assert!(result.is_ok());
1341 assert!(config.paper_balances.is_some());
1342 }
1343
1344 #[test]
1345 fn test_paper_init() {
1346 let mut state = PaperState::default();
1347 state.balances.insert("eth".into(), 100.0);
1348 state.next_order_id = 99;
1349
1350 let output = paper_init(&mut state, None, None).unwrap();
1351 assert_eq!(state.balances.get("idr"), Some(&100_000_000.0));
1352 assert_eq!(state.balances.get("btc"), Some(&1.0));
1353 assert_eq!(state.next_order_id, 1);
1354 assert_eq!(state.total_fees_paid, 0.0);
1355 assert!(state.initial_balances.is_some());
1356 assert!(output.render().contains("initialized"));
1357 }
1358
1359 #[test]
1360 fn test_paper_reset() {
1361 let mut state = PaperState {
1362 balances: { let mut m = std::collections::HashMap::new(); m.insert("custom".into(), 999.0); m },
1363 orders: vec![PaperOrder {
1364 id: 1, pair: "test".into(), side: "buy".into(), price: 1.0,
1365 amount: 1.0, remaining: 0.0, order_type: "limit".into(),
1366 status: "filled".into(), created_at: 0, fees_paid: 0.0, filled_price: 0.0,
1367 total_spent: 0.0,
1368 }],
1369 next_order_id: 50,
1370 trade_count: 10,
1371 total_fees_paid: 0.0,
1372 initial_balances: None,
1373 };
1374
1375 let output = paper_reset(&mut state).unwrap();
1376 assert_eq!(state.balances.get("idr"), Some(&100_000_000.0));
1377 assert_eq!(state.next_order_id, 1);
1378 assert_eq!(state.trade_count, 0);
1379 assert!(output.render().contains("reset"));
1380 }
1381
1382 #[test]
1383 fn test_paper_balance() {
1384 let mut state = PaperState::default();
1385 state.balances.insert("eth".into(), 5.0);
1386
1387 let output = paper_balance(&state).unwrap();
1388 let rendered = output.render();
1389 assert!(rendered.contains("IDR") || rendered.contains("BTC") || rendered.contains("ETH"));
1390 }
1391
1392 #[test]
1393 fn test_place_paper_order_buy() {
1394 let mut state = PaperState::default();
1395 let result = place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5);
1396
1397 assert!(result.is_ok());
1398 assert_eq!(state.balances.get("idr").unwrap(), &99950000.0);
1399 assert_eq!(state.balances.get("btc").unwrap(), &1.0);
1400 assert_eq!(state.orders.len(), 1);
1401 assert_eq!(state.trade_count, 1);
1402 assert_eq!(state.orders[0].status, "open");
1403 }
1404
1405 #[test]
1406 fn test_place_paper_order_sell() {
1407 let mut state = PaperState::default();
1408 let result = place_paper_order(&mut state, "btc_idr", "sell", Some(100_000_000.0), 0.5);
1409
1410 assert!(result.is_ok());
1411 assert_eq!(state.balances.get("btc").unwrap(), &0.5);
1412 assert_eq!(state.balances.get("idr").unwrap(), &100000000.0);
1413 assert_eq!(state.orders[0].status, "open");
1414 }
1415
1416 #[test]
1417 fn test_place_paper_order_insufficient_quote() {
1418 let mut state = PaperState::default();
1419 let result = place_paper_order(&mut state, "btc_idr", "buy", Some(200_000_000.0), 1.0);
1421
1422 assert!(result.is_err());
1423 assert!(result.unwrap_err().to_string().contains("Insufficient"));
1424 }
1425
1426 #[test]
1427 fn test_place_paper_order_insufficient_base() {
1428 let mut state = PaperState::default();
1429 let result = place_paper_order(&mut state, "btc_idr", "sell", Some(100_000_000.0), 2.0);
1431
1432 assert!(result.is_err());
1433 assert!(result.unwrap_err().to_string().contains("Insufficient"));
1434 }
1435
1436 #[test]
1437 fn test_paper_orders_empty() {
1438 let state = PaperState::default();
1439 let output = paper_orders(&state, None, None, None).unwrap();
1440 assert!(output.render().len() > 0);
1441 }
1442
1443 #[test]
1444 fn test_paper_orders_with_orders() {
1445 let mut state = PaperState::default();
1446 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5).unwrap();
1447 place_paper_order(&mut state, "btc_idr", "sell", Some(110_000_000.0), 0.3).unwrap();
1448
1449 let output = paper_orders(&state, None, None, None).unwrap();
1450 let rendered = output.render();
1451 assert!(rendered.contains("btc_idr"));
1452 }
1453
1454 #[test]
1455 fn test_paper_orders_filter_by_pair() {
1456 let mut state = PaperState::default();
1457 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5).unwrap();
1458 place_paper_order(&mut state, "eth_idr", "buy", Some(10_000_000.0), 1.0).unwrap();
1459
1460 let output = paper_orders(&state, Some("btc_idr"), None, None).unwrap();
1461 let rendered = output.render();
1462 assert!(rendered.contains("btc_idr"));
1463 assert!(!rendered.contains("eth_idr"));
1464 }
1465
1466 #[test]
1467 fn test_paper_cancel() {
1468 let mut state = PaperState::default();
1469 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5).unwrap();
1470 let order_id = state.orders[0].id;
1471
1472 let output = paper_cancel(&mut state, order_id);
1474 assert!(output.is_ok());
1475 assert_eq!(state.orders[0].status, "cancelled");
1476 assert_eq!(state.balances.get("idr").unwrap(), &100000000.0);
1477 }
1478
1479 #[test]
1480 fn test_paper_cancel_not_found() {
1481 let mut state = PaperState::default();
1482 let output = paper_cancel(&mut state, 999);
1483 assert!(output.is_err());
1484 }
1485
1486 #[test]
1487 fn test_paper_cancel_already_filled() {
1488 let mut state = PaperState::default();
1489 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5).unwrap();
1490 let order_id = state.orders[0].id;
1491
1492 paper_cancel(&mut state, order_id).unwrap();
1494 let output = paper_cancel(&mut state, order_id);
1496 assert!(output.is_err());
1497 assert!(output.unwrap_err().to_string().contains("already cancelled"));
1498 }
1499
1500 #[test]
1501 fn test_paper_cancel_all() {
1502 let mut state = PaperState::default();
1503 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5).unwrap();
1504 place_paper_order(&mut state, "eth_idr", "buy", Some(10_000_000.0), 1.0).unwrap();
1505
1506 let output = paper_cancel_all(&mut state);
1508 assert!(output.is_ok());
1509 assert_eq!(state.orders[0].status, "cancelled");
1510 assert_eq!(state.orders[1].status, "cancelled");
1511 }
1512
1513 #[test]
1514 fn test_paper_cancel_all_no_orders() {
1515 let mut state = PaperState::default();
1516 let output = paper_cancel_all(&mut state);
1517 assert!(output.is_ok());
1518 }
1519
1520 #[test]
1521 fn test_paper_history() {
1522 let mut state = PaperState::default();
1523 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5).unwrap();
1524
1525 let output = paper_history(&state, None, None).unwrap();
1526 assert!(output.render().len() > 0);
1527 }
1528
1529 #[test]
1530 fn test_paper_status() {
1531 let mut state = PaperState::default();
1532 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5).unwrap();
1533
1534 let output = paper_status(&state).unwrap();
1535 let rendered = output.render();
1536 assert!(rendered.contains("trade_count") || rendered.contains("Trade") || rendered.contains("BTC"));
1537 }
1538
1539 #[tokio::test]
1540 async fn test_paper_fill_buy() {
1541 let mut state = PaperState::default();
1542 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5).unwrap();
1543 let order_id = state.orders[0].id;
1544
1545 let result = paper_fill(&mut state, Some(order_id), None, false, None, false).await;
1546 assert!(result.is_ok());
1547 assert_eq!(state.orders[0].status, "filled");
1548 assert_eq!(state.orders[0].remaining, 0.0);
1549 }
1550
1551 #[tokio::test]
1552 async fn test_paper_fill_sell() {
1553 let mut state = PaperState::default();
1554 place_paper_order(&mut state, "btc_idr", "sell", Some(100_000_000.0), 0.5).unwrap();
1555 let order_id = state.orders[0].id;
1556
1557 let result = paper_fill(&mut state, Some(order_id), None, false, None, false).await;
1558 assert!(result.is_ok());
1559 assert_eq!(state.orders[0].status, "filled");
1560 }
1561
1562 #[tokio::test]
1563 async fn test_paper_fill_not_found() {
1564 let mut state = PaperState::default();
1565 let result = paper_fill(&mut state, Some(999), None, false, None, false).await;
1566 assert!(result.is_err());
1567 }
1568
1569 #[tokio::test]
1570 async fn test_paper_fill_already_filled() {
1571 let mut state = PaperState::default();
1572 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5).unwrap();
1573 let order_id = state.orders[0].id;
1574
1575 paper_fill(&mut state, Some(order_id), None, false, None, false).await.unwrap();
1576 let result = paper_fill(&mut state, Some(order_id), None, false, None, false).await;
1577 assert!(result.is_err());
1578 }
1579
1580 #[tokio::test]
1581 async fn test_paper_fill_with_custom_price() {
1582 let mut state = PaperState::default();
1583 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5).unwrap();
1584 let order_id = state.orders[0].id;
1585
1586 let result = paper_fill(&mut state, Some(order_id), Some(90_000.0), false, None, false).await;
1588 assert!(result.is_ok());
1589 assert_eq!(state.orders[0].status, "filled");
1590 assert_eq!(state.orders[0].filled_price, 90_000.0);
1591
1592 let result2 = paper_fill(&mut state, Some(order_id), Some(80_000.0), false, None, false).await;
1594 assert!(result2.is_err());
1595 }
1596
1597 #[tokio::test]
1598 async fn test_paper_fill_invalid_price_condition() {
1599 let mut state = PaperState::default();
1600 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5).unwrap();
1601 let order_id = state.orders[0].id;
1602
1603 let result = paper_fill(&mut state, Some(order_id), Some(110_000.0), false, None, false).await;
1605 assert!(result.is_err());
1606 assert_eq!(state.orders[0].status, "open");
1607 }
1608
1609 #[tokio::test]
1610 async fn test_paper_fill_all() {
1611 let mut state = PaperState::default();
1612 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5).unwrap();
1613 place_paper_order(&mut state, "btc_idr", "sell", Some(110_000_000.0), 0.3).unwrap();
1614
1615 let result = paper_fill(&mut state, None, None, true, None, false).await;
1616 assert!(result.is_ok());
1617 assert_eq!(state.orders[0].status, "filled");
1618 assert_eq!(state.orders[1].status, "filled");
1619 }
1620
1621 #[tokio::test]
1622 async fn test_paper_fill_all_no_open_orders() {
1623 let mut state = PaperState::default();
1624 let result = paper_fill(&mut state, None, None, true, None, false).await;
1625 assert!(result.is_ok());
1626 }
1627
1628 #[test]
1629 fn test_paper_topup_negative() {
1630 let mut state = PaperState::default();
1631 let result = paper_topup(&mut state, "idr", -5000.0);
1632 assert!(result.is_err(), "Negative topup should be rejected");
1633 assert!(result.unwrap_err().to_string().contains("positive"));
1634 }
1635
1636 #[test]
1637 fn test_place_paper_order_negative_amount() {
1638 let mut state = PaperState::default();
1639 let result = place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), -0.5);
1640 assert!(result.is_err());
1641 assert!(result.unwrap_err().to_string().contains("positive"));
1642 }
1643
1644 #[test]
1645 fn test_place_paper_order_negative_price() {
1646 let mut state = PaperState::default();
1647 let result = place_paper_order(&mut state, "btc_idr", "buy", Some(-100.0), 0.5);
1648 assert!(result.is_err());
1649 assert!(result.unwrap_err().to_string().contains("positive"));
1650 }
1651
1652 #[test]
1653 fn test_place_paper_order_zero_amount() {
1654 let mut state = PaperState::default();
1655 let result = place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.0);
1656 assert!(result.is_err());
1657 assert!(result.unwrap_err().to_string().contains("positive"));
1658 }
1659
1660 #[test]
1661 fn test_execute_fill_buy() {
1662 let mut state = PaperState::default();
1663 state.balances.insert("btc".into(), 0.0);
1664 state.balances.insert("idr".into(), 100_000_000.0);
1665
1666 let result = execute_fill(&mut state, 1, "btc", "idr", "buy", 100_000.0, 0.5);
1667 assert!(result.is_ok());
1668 assert_eq!(state.balances.get("btc").unwrap(), &0.5);
1669 }
1670
1671 #[test]
1672 fn test_execute_fill_sell() {
1673 let mut state = PaperState::default();
1674 state.balances.insert("btc".into(), 1.0);
1675 state.balances.insert("idr".into(), 0.0);
1676
1677 let result = execute_fill(&mut state, 1, "btc", "idr", "sell", 100_000_000.0, 0.5);
1678 assert!(result.is_ok());
1679 assert_eq!(state.balances.get("idr").unwrap(), &49870000.0);
1680 }
1681
1682 #[test]
1683 fn test_paper_order_fields() {
1684 let order = PaperOrder {
1685 id: 1,
1686 pair: "btc_idr".into(),
1687 side: "buy".into(),
1688 price: 100_000.0,
1689 amount: 0.5,
1690 remaining: 0.0,
1691 order_type: "limit".into(),
1692 status: "filled".into(),
1693 created_at: 12345,
1694 fees_paid: 0.0,
1695 filled_price: 100_000.0,
1696 total_spent: 0.0,
1697 };
1698
1699 assert_eq!(order.id, 1);
1700 assert_eq!(order.pair, "btc_idr");
1701 assert_eq!(order.side, "buy");
1702 assert_eq!(order.total_spent, 0.0);
1703 }
1704
1705 #[tokio::test]
1706 async fn test_dispatch_paper_init() {
1707 let client = IndodaxClient::new(None).unwrap();
1708 let mut state = PaperState::default();
1709 let mut config = IndodaxConfig::default();
1710 let cmd = PaperCommand::Init { idr: None, btc: None };
1711 let result = dispatch_paper(&client, &mut state, &mut config, &cmd).await;
1712 assert!(result.is_ok());
1713 }
1714
1715 #[tokio::test]
1716 async fn test_dispatch_paper_balance() {
1717 let client = IndodaxClient::new(None).unwrap();
1718 let state = PaperState::default();
1719 let mut config = IndodaxConfig::default();
1720 let cmd = PaperCommand::Balance;
1721 let result = dispatch_paper(&client, &mut state.clone(), &mut config, &cmd).await;
1722 assert!(result.is_ok());
1723 }
1724
1725 #[tokio::test]
1726 async fn test_paper_check_fills_buy_match() {
1727 let client = IndodaxClient::new(None).unwrap();
1728 let mut state = PaperState::default();
1729 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000_000.0), 0.5).unwrap();
1730 let prices = r#"{"btc_idr": 90000000}"#;
1731
1732 let result = paper_check_fills(&client, &mut state, Some(prices), false).await;
1733 assert!(result.is_ok());
1734 assert_eq!(state.orders[0].status, "filled");
1735 }
1736
1737 #[tokio::test]
1738 async fn test_paper_check_fills_buy_no_match() {
1739 let client = IndodaxClient::new(None).unwrap();
1740 let mut state = PaperState::default();
1741 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000_000.0), 0.5).unwrap();
1742 let prices = r#"{"btc_idr": 110000000}"#;
1743
1744 let result = paper_check_fills(&client, &mut state, Some(prices), false).await;
1745 assert!(result.is_ok());
1746 assert_eq!(state.orders[0].status, "open");
1747 }
1748
1749 #[tokio::test]
1750 async fn test_paper_check_fills_sell_match() {
1751 let client = IndodaxClient::new(None).unwrap();
1752 let mut state = PaperState::default();
1753 place_paper_order(&mut state, "btc_idr", "sell", Some(100_000_000.0), 0.5).unwrap();
1754 let prices = r#"{"btc_idr": 110000000}"#;
1755
1756 let result = paper_check_fills(&client, &mut state, Some(prices), false).await;
1757 assert!(result.is_ok());
1758 assert_eq!(state.orders[0].status, "filled");
1759 }
1760
1761 #[tokio::test]
1762 async fn test_paper_check_fills_multiple_orders() {
1763 let client = IndodaxClient::new(None).unwrap();
1764 let mut state = PaperState::default();
1765 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000_000.0), 0.5).unwrap();
1766 place_paper_order(&mut state, "eth_idr", "buy", Some(10_000_000.0), 1.0).unwrap();
1767 place_paper_order(&mut state, "btc_idr", "sell", Some(120_000_000.0), 0.3).unwrap();
1768 let prices = r#"{"btc_idr": 90000000, "eth_idr": 15000000}"#;
1769
1770 let result = paper_check_fills(&client, &mut state, Some(prices), false).await;
1771 assert!(result.is_ok());
1772 assert_eq!(state.orders[0].status, "filled");
1774 assert_eq!(state.orders[1].status, "open");
1775 assert_eq!(state.orders[2].status, "open");
1776 }
1777
1778 #[tokio::test]
1779 async fn test_paper_check_fills_invalid_json() {
1780 let client = IndodaxClient::new(None).unwrap();
1781 let mut state = PaperState::default();
1782 let result = paper_check_fills(&client, &mut state, Some("not-json"), false).await;
1783 assert!(result.is_err());
1784 }
1785
1786 #[tokio::test]
1787 async fn test_paper_check_fills_empty_prices() {
1788 let client = IndodaxClient::new(None).unwrap();
1789 let mut state = PaperState::default();
1790 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000_000.0), 0.5).unwrap();
1791 let result = paper_check_fills(&client, &mut state, Some(r#"{}"#), false).await;
1792 assert!(result.is_ok());
1793 assert_eq!(state.orders[0].status, "open");
1794 }
1795
1796 #[tokio::test]
1797 async fn test_paper_check_fills_no_open_orders() {
1798 let client = IndodaxClient::new(None).unwrap();
1799 let mut state = PaperState::default();
1800 let result = paper_check_fills(&client, &mut state, Some(r#"{"btc_idr": 90000000}"#), false).await;
1801 assert!(result.is_ok());
1802 }
1803
1804 #[tokio::test]
1805 async fn test_paper_check_fills_fetch_not_available() {
1806 let client = IndodaxClient::new(None).unwrap();
1807 let mut state = PaperState::default();
1808 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000_000.0), 0.5).unwrap();
1809 let result = paper_check_fills(&client, &mut state, None, true).await;
1812 assert!(result.is_ok(), "Should handle fetch failure without error: {:?}", result.err());
1813 assert_eq!(state.orders[0].status, "open", "Order should remain open when prices unavailable");
1814 assert_eq!(state.orders[0].remaining, 0.5, "Remaining amount should be unchanged");
1815 }
1816
1817 #[tokio::test]
1818 async fn test_paper_lifecycle_buy_fill_cancel() {
1819 let mut state = PaperState::default();
1820 let initial_idr = *state.balances.get("idr").unwrap();
1821 let initial_btc = *state.balances.get("btc").unwrap();
1822
1823 let result = place_paper_order(&mut state, "btc_idr", "buy", Some(100_000.0), 0.5);
1825 assert!(result.is_ok());
1826 let order_id = state.orders[0].id;
1827 assert_eq!(state.orders[0].status, "open");
1828 assert!(*state.balances.get("idr").unwrap() < initial_idr);
1830
1831 let result = paper_fill(&mut state, Some(order_id), None, false, None, false).await;
1833 assert!(result.is_ok());
1834 assert_eq!(state.orders[0].status, "filled");
1835 assert!(*state.balances.get("btc").unwrap() > initial_btc);
1837
1838 let result = paper_cancel(&mut state, order_id);
1840 assert!(result.is_err());
1841
1842 let output = paper_orders(&state, None, None, None).unwrap();
1844 assert!(!output.render().contains("filled"));
1845 let history = paper_history(&state, None, None).unwrap();
1847 assert!(history.render().contains("filled"));
1848 }
1849
1850 #[test]
1851 fn test_paper_lifecycle_sell_cancel_topup() {
1852 let mut state = PaperState::default();
1853
1854 let result = place_paper_order(&mut state, "btc_idr", "sell", Some(100_000_000.0), 0.5);
1856 assert!(result.is_ok());
1857 let order_id = state.orders[0].id;
1858 assert_eq!(state.orders[0].status, "open");
1859
1860 let btc_before = *state.balances.get("btc").unwrap();
1862 let result = paper_cancel(&mut state, order_id);
1863 assert!(result.is_ok());
1864 assert_eq!(state.orders[0].status, "cancelled");
1865 assert!(*state.balances.get("btc").unwrap() > btc_before);
1866
1867 let result = paper_topup(&mut state, "usdt", 1000.0);
1869 assert!(result.is_ok());
1870 assert_eq!(*state.balances.get("usdt").unwrap(), 1000.0);
1871
1872 let output = paper_status(&state).unwrap();
1874 let rendered = output.render();
1875 assert!(rendered.contains("cancelled") || rendered.contains("Cancelled"));
1876 }
1877
1878 #[tokio::test]
1879 async fn test_paper_lifecycle_multiple_orders_and_check_fills() {
1880 let client = IndodaxClient::new(None).unwrap();
1881 let mut state = PaperState::default();
1882
1883 state.balances.insert("eth".into(), 5.0);
1885
1886 place_paper_order(&mut state, "btc_idr", "buy", Some(100_000_000.0), 0.5).unwrap();
1888 place_paper_order(&mut state, "eth_idr", "sell", Some(10_000_000.0), 2.0).unwrap();
1889 place_paper_order(&mut state, "btc_idr", "buy", Some(90_000_000.0), 0.3).unwrap();
1890
1891 let prices = r#"{"btc_idr": 95000000, "eth_idr": 12000000}"#;
1893 let result = paper_check_fills(&client, &mut state, Some(prices), false).await;
1894 assert!(result.is_ok());
1895
1896 assert_eq!(state.orders[0].status, "filled");
1898 assert_eq!(state.orders[1].status, "filled");
1900 assert_eq!(state.orders[2].status, "open");
1902
1903 let result = paper_fill(&mut state, None, None, true, None, false).await;
1905 assert!(result.is_ok());
1906 assert_eq!(state.orders[2].status, "filled");
1907 }
1908}