Infinite loop in make_offer if you run > 5 loops in main

This commit is contained in:
2024-05-19 09:47:40 -04:00
parent 9ac396795c
commit 86a7fcd698
4 changed files with 36 additions and 279 deletions

View File

@@ -1,6 +1,8 @@
use std::collections::HashMap;
use std::cmp::Ordering;
use std::cmp::min;
use rand::prelude::*;
use rand::rngs::StdRng;
use finum::FiNum;
#[derive(Debug, Clone)]
@@ -48,12 +50,6 @@ impl Dumpable for Offer {
}
impl Offer {
fn dump(self) {
println!("Remaining: {} Price: {}",self.sell_remain,self.buy_qty/self.sell_qty);
}
}
struct Market {
asset_name2num: HashMap<String,i32>,
asset_num2name: HashMap<i32,String>,
@@ -126,9 +122,17 @@ impl Market {
println!(" {}: {}",self.number_to_name(*cur),*bal)
}
}
for (key,value) in &self.offers {
println!("Offers selling {} to buy {}:",self.number_to_name(key.0),self.number_to_name(key.1));
value.dump();
for (ap,pq) in &self.offers {
println!("Offers selling {} to buy {}:",self.number_to_name(ap.0),self.number_to_name(ap.1));
let mut sorted=pq.v.clone();
sorted.sort_by(|a,b| (a.sell_qty/a.buy_qty).cmp(&(b.sell_qty/b.buy_qty)));
for off in sorted.iter() {
println!(" {} @ {} ({})",
off.buy_qty*(off.sell_remain/off.sell_qty),
off.sell_qty/off.buy_qty,
self.traders[off.owner as usize].name);
}
//value.dump();
}
}
fn make_offer(&mut self, owner:i32, sell_type:i32, buy_type:i32, sell_qty_initial:FiNum, buy_qty_initial:FiNum) -> bool // Dollars, Bitcoin, 64000, 1
@@ -241,20 +245,31 @@ impl<T: Dumpable + std::cmp::PartialOrd + std::fmt::Debug> PQueue<T> {
fn main() {
let a=FiNum::new_i32(2);
let b=FiNum::new_i32(3);
let c=b+a;
println!("C is {}, C.value() is {}",c,c.value());
let mut rng: StdRng=StdRng::seed_from_u64(1u64);
let mut m=Market::new(); // USD type is 1, EUR type is 2, BTC type is 10, ETH type is 11, SOL type is 12
let teppy=m.register_trader("Teppy");
let luni =m.register_trader("Luni");
let usd =m.register_asset("USD");
let btc =m.register_asset("BTC");
m.add_trader_balance(teppy,btc,5.into());
m.add_trader_balance(luni ,usd,300000.into());
m.make_offer(teppy,btc,usd,1.into(),60000.into());
m.sanity_check();
m.make_offer(luni ,usd,btc,128000.into(),2.into()); // Buy 1 BTC for 64000 USD
m.add_trader_balance(teppy,btc,100.into());
m.add_trader_balance(luni ,usd,1000000.into());
for i in 1..=5 {
let seller=if rng.gen_bool(0.5) { teppy } else { luni };
let (buy_type,sell_type,buy_qty,sell_qty):(i32,i32,FiNum,FiNum);
if rng.gen_bool(0.5) {
sell_type=btc;
buy_type=usd;
sell_qty=rng.gen_range(2..=5).into();
buy_qty=sell_qty*rng.gen_range(60000..=70000).into();
} else {
sell_type=usd;
buy_type=btc;
buy_qty=rng.gen_range(2..=5).into();
sell_qty=buy_qty*rng.gen_range(60000..=70000).into();
}
println!("Sell {} {} to buy {} {} ({})",sell_qty,m.number_to_name(sell_type),buy_qty,m.number_to_name(buy_type),m.traders[seller as usize].name);
m.make_offer(seller,sell_type,buy_type,sell_qty,buy_qty);
}
m.dump();
m.sanity_check();
}