use std::collections::HashMap; use std::cmp::Ordering; use std::cmp::min; use fixed::types::U32F32; #[derive(Debug, Clone)] struct Trader { name: String, id: i32, balances: HashMap, // Maps Currency to Amount } impl Trader { fn new(name:&str,id:i32) -> Self { Trader { name: String::from(name), id: id, balances: HashMap::new() } } fn add_balance(&mut self, cur:i32, delta:u64) { self.balances.entry(cur).and_modify(|ent| *ent+=delta ).or_insert_with(|| delta); } fn sub_balance(&mut self, cur:i32, delta:u64) { self.balances.entry(cur).and_modify(|ent| *ent-=delta ); } fn get_balance(&self, cur:i32) -> u64 { *self.balances.get(&cur).map(|bal| bal).unwrap_or(&0u64) } } #[derive(Debug, Clone)] struct Offer { sell_qty: u64, sell_remain: u64, buy_qty: u64, owner: i32, } trait Dumpable { fn dump(&self); } impl Dumpable for Offer { fn dump(&self) { println!("Giving {}/{} to get {}",fxp_to_fp(self.sell_remain),fxp_to_fp(self.sell_qty),fxp_to_fp(self.buy_qty)); } } impl Offer { fn dump(self) { println!("Remaining: {} Price: {}",self.sell_remain,fxp_to_fp(fxp_div(self.buy_qty,self.sell_qty))); } } struct Market { asset_name2num: HashMap, asset_num2name: HashMap, asset_count:i32, offers: HashMap<(i32,i32),PQueue>, traders: Vec, } impl Market { fn new() -> Self { Market { asset_name2num: HashMap::new(), asset_num2name: HashMap::new(), asset_count:0, offers: HashMap::new(), traders: Vec::new() } } fn register_asset(&mut self, name:&str) -> i32 { self.asset_count+=1; self.asset_name2num.insert(String::from(name),self.asset_count); self.asset_num2name.insert(self.asset_count,String::from(name)); self.asset_count } fn name_to_number(&self, name:&str) -> i32 { *self.asset_name2num.get(name).unwrap() } fn number_to_name(&self, num:i32) -> &str { &*self.asset_num2name.get(&num).unwrap() } fn dump(&self) { println!("Dumping Market:"); 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(); } } fn make_offer(&mut self, owner:i32, sell_type:i32, buy_type:i32, sell_qty_initial:u64, buy_qty_initial:u64) // Dollars, Bitcoin, 64000, 1 { // Comments assume someone is already selling 1 Bitcoin for 48000 USD (Bitcoin, Dollars, 1, 48000). Then someone comes along and bids $64000 for 1 Bitcoin (sells 64000 USD to buy 1 Bitcoin. println!("Making offer to sell {} {} and get {} {}",fxp_to_fp(sell_qty_initial),self.number_to_name(sell_type),fxp_to_fp(buy_qty_initial),self.number_to_name(buy_type)); let mut sell_qty=sell_qty_initial; // 64000 Dollars let mut buy_qty=buy_qty_initial; // 1 Bitcoin let sell_rate=fxp_div(sell_qty,buy_qty); let ap=(buy_type,sell_type); let mut lc=3; while sell_qty>0 && lc>0 { if let Some(asks)=self.offers.get_mut(&ap) { if asks.v.len()>0 { let elt=&mut asks.v[0]; let ask_rate=fxp_div(elt.buy_qty,elt.sell_qty); let elt_buy_remain=fxp_mult(elt.buy_qty,fxp_div(elt.sell_remain,elt.sell_qty)); if sell_rate>=ask_rate { // Transact at ask_rate // Can we eat the entire ask? if buy_qty>=elt.sell_remain { sell_qty-=fxp_mult(sell_qty,fxp_div(elt.sell_remain,buy_qty_initial)); buy_qty-=elt.sell_remain; asks.pop(); } else if elt_buy_remain>=sell_qty { // Can we eat the rest of the offer? elt.sell_remain-=buy_qty; sell_qty=0; buy_qty=0; } else { let transact=std::cmp::min(sell_qty,fxp_mult(elt.buy_qty,fxp_div(elt.sell_remain,elt.sell_qty))); elt.sell_remain-=fxp_div(transact,ask_rate); buy_qty-=fxp_div(transact,ask_rate); sell_qty-=fxp_mult(transact,fxp_div(sell_rate,ask_rate)); if elt.sell_remain==0 { println!("Popping asks"); asks.pop(); } } } else { break; } } else { break; } } else { break; } lc-=1; } if sell_qty>0 { let ap=(sell_type,buy_type); if let None=self.offers.get_mut(&ap) { self.offers.insert(ap,PQueue::new()); } let mut bids=self.offers.get_mut(&ap).unwrap(); println!("Inserting new offer with sell_qty {}, buy_qty {}",fxp_to_fp(sell_qty),fxp_to_fp(buy_qty)); bids.insert(Offer { owner:owner, sell_qty:sell_qty, sell_remain:sell_qty, buy_qty:buy_qty } ); } } } impl PartialOrd for Offer { fn partial_cmp(&self, other:&Self) -> Option { let ord0=self .sell_qty/self .buy_qty; let ord1=other.buy_qty /other.sell_qty; if ord0ord1 { Some(Ordering::Greater) } else { Some(Ordering::Equal) } } } impl PartialEq for Offer { fn eq(&self, other:&Self) -> bool { let ord0=self .sell_qty/self .buy_qty; let ord1=other.sell_qty/other.buy_qty; ord0==ord1 } } struct PQueue { v: Vec, } impl PQueue { fn new()->Self { PQueue { v: Vec::new() } } fn peek(&self) -> &T { &self.v[0] } fn bubble_up(&mut self, pos: usize) { if pos>0 { let parent=(pos-1)/2; if self.v[parent] Option { if self.v.len()==0 { None } else { let end=self.v.len()-1; self.v.swap(0,end); let rval=self.v.pop(); self.trickle_down(0); rval } } fn dump(&self) { for index in 0..self.v.len() { self.v[index].dump(); } } } //fn fxp_mult(n0:u64, n1:u64) ->u64 { (((n0>>32)*(n1>>32))<<64)+(((n0>>32)*(n1&0xFFFFFFFF))<<32)+(((n0&0xFFFFFFFF)*(n1>>32))<<32)+(n0&0xFFFFFFFF)*(n1&0xFFFFFFFF) } fn fxp_div(n0:u64, n1:u64) -> u64 { fxp_mult(n0,fxp_recip(n1)) } fn fxp_from_int(n:u32) -> u64 { (n as u64)<<32 } fn fxp_recip(n:u64) -> u64 { 0xFFFFFFFFFFFFFFFFu64/n } fn fxp_to_fp(n:u64) -> f64 { (n as f64)/(1u64<<32) as f64 } fn fxp_mult(a: u64, b: u64) -> u64 { let a_high = a >> 32; let a_low = a & 0xFFFFFFFF; let b_high = b >> 32; let b_low = b & 0xFFFFFFFF; let high_high = a_high * b_high; let high_low = a_high * b_low; let low_high = a_low * b_high; let low_low = a_low * b_low; let mid_term = high_low + low_high; let carry = mid_term >> 32; let result_high = high_high + carry; let result_low = (mid_term << 32) + low_low; (result_high << 32) | (result_low >> 32) } fn main() { let mut t1=Trader::new("Teppy",1); t1.add_balance(1,100); t1.add_balance(2,150); t1.sub_balance(1, 25); println!("Balances are {} and {}",t1.get_balance(1),t1.get_balance(2)); 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 usd=m.register_asset("USD"); let btc=m.register_asset("BTC"); let n=64000u64<<32; println!("This should be 64000: {} or in raw form {}",fxp_to_fp(n),n); println!("This should be 1/64000: {} or in raw form {}",fxp_to_fp(fxp_recip(n)),fxp_recip(n)); println!("This should be 64000: {} or in raw form {}",fxp_to_fp(fxp_recip(fxp_recip(n))),fxp_recip(fxp_recip(n))); println!("This should be 1: {} or in raw form ",fxp_to_fp(fxp_mult(fxp_recip(fxp_from_int(64000)),fxp_from_int(64000)))); println!("{}*{}={}",fxp_to_fp(fxp_from_int(3)),fxp_to_fp(fxp_from_int(5)),fxp_to_fp(fxp_mult(fxp_from_int(3),fxp_from_int(5)))); m.make_offer(0,btc,usd,fxp_from_int(1),fxp_from_int(60000)); m.dump(); m.make_offer(1,usd,btc,fxp_from_int(128000),fxp_from_int(2)); // Buy 1 BTC for 64000 USD m.dump(); }