// // When inserting a new Order into the royalties tree, we must make sure the existing // royalties don't get shared with that new node. To do this, we must "shave" down // the tree, pushing royalties from the root down to all nodes to the left of the // new node. // // Case to think about: // Selling 140000 USD to buy 2 BTC. Weight is ===140k USD // Selling 50000 GBP to buy 1 BTC. Weight is === 50k GBP // #![allow(unsafe_code)] #![allow(unused_variables)] #![allow(dead_code)] use std::io::{self, BufRead}; use std::env; use std::collections::HashMap; use std::cmp::Ordering; use std::rc::Rc; use std::cell::RefCell; use rand::prelude::*; use rand::rngs::StdRng; use finum::FiNum; #[derive(Debug, Clone)] struct Trader { name: String, password: String, // hash(name..salt..password) id: usize, balances: HashMap, // Maps Currency to Amount } #[derive(Clone)] struct Asset { name: String, royalty0_rate: FiNum, // Traders get this when entered royalty1_rate: FiNum, // Traders get this when executed commission0_rate: FiNum, // House gets this when entered commission1_rate: FiNum, // House gets this when executed } impl Asset { fn new(name: &str) -> Self { Asset { name: String::from(name), royalty0_rate:FiNum::zero(), royalty1_rate:FiNum::zero(), commission0_rate:FiNum::zero(), commission1_rate:FiNum::zero(), } } } impl Trader { fn new(name:&str,id:usize) -> Self { Trader { name: String::from(name), password: String::from(""), id: id, balances: HashMap::new() } } fn add_balance(&mut self, cur:usize, delta:FiNum) { self.balances.entry(cur).and_modify(|ent| *ent+=delta ).or_insert_with(|| delta); } fn sub_balance(&mut self, cur:usize, delta:FiNum) { self.balances.entry(cur).and_modify(|ent| *ent-=delta ); } fn get_balance(&self, cur:usize) -> FiNum { *self.balances.get(&cur).map(|bal| bal).unwrap_or(&FiNum::new(0u64)) } } #[derive(Debug, Clone)] struct Order { sell_qty: FiNum, sell_remain: FiNum, buy_qty: FiNum, royalty_remain: FiNum, // Based on royalty1 commission_remain: FiNum, // Based on commission1 owner: usize, rt_loc: usize, // Location in the Royalty Tree } struct RoyaltyTree { tree: Vec, next_entry: usize, spare_change: FiNum, // Waiting to be distributed } struct Royalty { weight: FiNum, // Here and below lazy: FiNum, // To be distributed to here and to below based on weights acc: FiNum, // Accumulated here } impl Royalty { fn new() -> Self { Royalty { weight:FiNum::zero(), lazy:FiNum::zero(), acc:FiNum::zero() } } } impl RoyaltyTree { fn new() -> Self { RoyaltyTree { tree:Vec::new(), next_entry:0, spare_change:FiNum::zero() } } fn weight_here_below(&self, index:usize) -> FiNum { self.tree[index].weight } fn weight_below(&self, index: usize) -> FiNum { if index&1==0 { FiNum::zero() } else { let w0=self.weight_here_below(wt_left (index).unwrap()); let w1=self.weight_here_below(wt_right(index).unwrap()); w0+w1 } } fn weight_here(&self, index:usize) -> FiNum { if index&1==0 { self.weight_here_below(index) } else { let w0=self.weight_here_below(index); let w1=self.weight_below(index); w0-w1 } } fn expand_to(&mut self, index: usize) -> &mut Self { for _ in self.tree.len()..=index { self.tree.push(Royalty::new()) } self } fn capture0(&mut self, index: usize) -> &mut Self { if index&1==0 { let lazy=self.tree[index].lazy; self.tree[index].acc+=lazy; self.tree[index].lazy=FiNum::zero(); } else { let lazy=self.tree[index].lazy; let d1=if lazy>0.into() { lazy*self.weight_here(index)/self.weight_here_below(index) } else { FiNum::zero() }; let d02=lazy-d1; let index_left =wt_left (index).unwrap(); let index_right=wt_right(index).unwrap(); let d0=if d02>0.into() { d02*self.weight_here_below(index_left)/self.weight_below(index) } else { FiNum::zero() }; let d2=d02-d0; assert!(lazy==d0+d1+d2,"Distributing amounts that don't add up."); self.tree[index_left ].lazy+=d0; self.tree[index_right].lazy+=d2; self.tree[index].acc+=d1; self.tree[index].lazy=FiNum::zero(); } self } fn get_royalty(&mut self, index: usize) -> FiNum { let mut f=self.forefather(); while f!=index { self.capture0(f); f=if f>index { wt_left(f).unwrap() } else { wt_right(f).unwrap() } } self.capture0(f); self.tree[index].acc } fn add_royalty(&mut self, amount: FiNum) { if self.next_entry==0 { self.spare_change+=amount } else { let ff=self.forefather(); if self.weight_here_below(ff).is_zero() { self.spare_change+=amount } else { self.tree[ff].lazy+=amount }; } } fn add_weight(&mut self, index: usize, weight: FiNum) { if self.tree.len()>0 { let mut ff0=self.forefather(); let ff1=wt_forefather(index); let w=self.tree[ff0].weight; self.expand_to(ff1*2); while ff0 usize { wt_forefather(self.tree.len()-1) } fn dump(&mut self) { for index in 0..self.tree.len() { let roy=self.get_royalty(index); println!("Index {} Weight {} Lazy {} Acc {} Royalty {}",index,self.tree[index].weight,self.tree[index].lazy,self.tree[index].acc,roy); } } } trait Dumpable { fn dump(&self); } impl Dumpable for usize { fn dump(&self) { println!("Dump Integer: {}",self); } } impl Dumpable for Rc> { fn dump(&self) { } } impl Dumpable for Order { fn dump(&self) { println!("Giving {}/{} to get {}",self.sell_remain,self.sell_qty,self.buy_qty); } } struct Market { asset_name2num: HashMap, assets: Vec, money_supply: HashMap, traders: Vec, trader_name2num: HashMap, orders: HashMap<(usize,usize),PQueue>>>, royalties: HashMap, // Active orders that are accepting asset X. They receive royalties when someone makes an order to sell X royalty_rate: HashMap, } impl Market { fn new() -> Self { let mut rval=Market { asset_name2num: HashMap::new(), assets: Vec::new(), money_supply: HashMap::new(), traders: Vec::new(), trader_name2num: HashMap::new(), orders: HashMap::new(), royalties: HashMap::new(), royalty_rate: HashMap::new(), }; rval.register_trader("*HOUSE*"); rval } fn sanity_check(&self) { println!("Sanity Checking Market..."); for (cur,amt) in self.money_supply.iter() { println!("Money Supply {}: {}",self.number_to_name(*cur),*amt); let mut acc_orders=FiNum::new(0); for (ac,pq) in &self.orders { if ac.0==*cur { for off in &*pq.v { acc_orders+=off.borrow().sell_remain; } } } let mut acc_traders=FiNum::new(0); for t in &self.traders { acc_traders+=t.get_balance(*cur); } let acc=acc_orders+acc_traders; println!(" {}: Orders {} Traders {} Total {} Should Be {}",self.number_to_name(*cur),acc_orders,acc_traders,acc,*amt); } } fn register_trader(&mut self, name:&str) -> usize { // Add error checking for inserting a trader twice let rval=self.traders.len(); self.trader_name2num.insert(String::from(name),self.traders.len()); self.traders.push(Trader::new(name,rval)); rval } // These are the only ways to get money into or out of the market. fn add_trader_balance(&mut self, who:usize, cur:usize, delta: FiNum) { self.traders[who as usize].add_balance(cur,delta); *self.money_supply.get_mut(&cur).unwrap()+=delta; } fn sub_trader_balance(&mut self, who:usize, cur:usize, delta: FiNum) { self.traders[who as usize].sub_balance(cur,delta); *self.money_supply.get_mut(&cur).unwrap()-=delta; } fn register_asset(&mut self, name:&str) -> Option { if self.asset_name2num.contains_key(name) { return None } self.assets.push(Asset::new(name)); self.asset_name2num.insert(String::from(name),self.assets.len()-1); self.money_supply.insert(self.assets.len()-1,FiNum::new(0)); let rval=self.assets.len()-1; Some(rval) } fn number_to_asset(&self, n: usize) -> Asset { self.assets[n].clone() } fn number_to_name(&self, n: usize) -> String { self.assets[n].name.clone() } fn name_to_number(&self, name:&str) -> Option<&usize> { self.asset_name2num.get(name) } fn dump(&self) { println!("Dumping Market:"); for t in &self.traders { println!(" Trader {}: {}",t.id,t.name); for (cur,bal) in t.balances.iter() { println!(" {}: {}",self.number_to_name(*cur),*bal) } } for (ap,pq) in &self.orders { println!("Orders 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| { let a=a.borrow(); let b=b.borrow(); (a.sell_qty/a.buy_qty).cmp(&(b.sell_qty/b.buy_qty)) }); for off in sorted.iter() { let off=off.borrow(); println!(" {} @ {} ({})", off.sell_remain, // off.buy_qty*off.sell_remain/off.sell_qty, off.buy_qty/off.sell_qty, self.traders[off.owner as usize].name); } pq.dump(); } } fn make_order(&mut self, owner:usize, sell_type:usize, buy_type:usize, sell_qty_initial:FiNum, buy_qty_initial:FiNum) -> bool // Dollars, Bitcoin, 64000, 1 { let initial_balance=self.traders[owner].get_balance(sell_type); let asset=self.number_to_asset(sell_type); let mut royalty0_qty=asset.royalty0_rate*sell_qty_initial; let mut royalty1_qty=asset.royalty1_rate*sell_qty_initial; let mut commission0_qty=asset.commission0_rate*sell_qty_initial; let mut commission1_qty=asset.commission1_rate*sell_qty_initial; let sell_qty_plus=sell_qty_initial+royalty0_qty+royalty1_qty+commission0_qty+commission1_qty; // This is the maximum amount we are going to sell let sell_qty=sell_qty_initial; if initial_balanceFiNum::new(0) && self.orders.contains_key(&ap) && self.orders.get(&ap).unwrap().v.len()>0 { let mut elt=(*(self.orders.get(&ap).unwrap().v[0].borrow())).clone(); if sell_qty/buy_qty_initial>=elt.buy_qty/elt.sell_qty { // Transact at ask_rate let qty=std::cmp::min(elt.sell_remain,buy_qty); elt.sell_remain-=qty; buy_qty-=qty; let pay_qty=qty*elt.buy_qty/elt.sell_qty; self.traders[owner ].sub_balance(sell_type,pay_qty); self.traders[owner ].add_balance(buy_type ,qty); self.traders[elt.owner].add_balance(sell_type,pay_qty); let rq0=royalty0_qty *pay_qty/sell_qty_initial; let cq0=commission0_qty*pay_qty/sell_qty_initial; let rq1=royalty1_qty *pay_qty/sell_qty_initial; let cq1=commission1_qty*pay_qty/sell_qty_initial; let rq2=elt.royalty_remain*qty/elt.sell_remain; let cq2=elt.commission_remain*qty/elt.sell_remain; royalty_acc+=rq0+rq1; commission_acc+=cq0+cq1; royalty0_qty-=rq0; royalty1_qty-=rq1; commission0_qty-=cq0; commission1_qty-=cq1; self.royalties.entry(sell_type).or_insert(RoyaltyTree::new()).add_royalty(rq0+rq1); self.royalties.entry(buy_type) .or_insert(RoyaltyTree::new()).add_royalty(rq2); self.orders.get(&ap).unwrap().v[0].borrow_mut().royalty_remain-=rq2; self.orders.get(&ap).unwrap().v[0].borrow_mut().commission_remain-=cq2; self.traders[0].add_balance(buy_type,cq2); self.royalties.entry(buy_type).or_insert(RoyaltyTree::new()).add_royalty(rq2); if elt.sell_remain==0.into() { // deal with pennies stored in royalty_remain and commission_remain self.traders[0].add_balance(buy_type,self.orders.get(&ap).unwrap().v[0].borrow_mut().commission_remain); self.royalties.entry(buy_type).or_insert(RoyaltyTree::new()).add_royalty(self.orders.get(&ap).unwrap().v[0].borrow_mut().royalty_remain); self.orders.get_mut(&ap).unwrap().pop(); } else { self.orders.get(&ap).unwrap().v[0].borrow_mut().sell_remain-=qty; } } else { break; } } if buy_qty>0.into() { let ap=(sell_type,buy_type); if let None=self.orders.get_mut(&ap) { self.orders.insert(ap,PQueue::new()); } let bids=self.orders.get_mut(&ap).unwrap(); let sell_qty_remain=sell_qty*buy_qty/buy_qty_initial; if sell_qty_remain>0.into() { self.royalties.entry(sell_type).or_insert(RoyaltyTree::new()).add_royalty(royalty0_qty); let rt=self.royalties.entry(buy_type).or_insert(RoyaltyTree::new()); rt.add_weight(rt.next_entry,buy_qty); // Weight should really be the quantity you would be able to immediately transact rather than how much you wish for. let neworder=Rc::new(RefCell::new( Order { owner:owner, sell_qty:sell_qty_remain, sell_remain:sell_qty_remain, buy_qty:buy_qty, rt_loc: rt.next_entry, royalty_remain:royalty1_qty, commission_remain:commission1_qty } )); rt.next_entry+=1; bids.insert(neworder); self.traders[owner].sub_balance(sell_type,sell_qty_remain); self.traders[0].add_balance(sell_type,commission0_qty); } } self.traders[0].add_balance(sell_type,commission_acc); self.traders[owner].sub_balance(sell_type,royalty_acc+commission_acc); true } } impl PartialOrd for Order { fn partial_cmp(&self, other:&Self) -> Option { let ord0=self .sell_qty/self .buy_qty; let ord1=other.sell_qty/other.buy_qty; if ord0ord1 { Some(Ordering::Greater) } else { Some(Ordering::Equal) } } } impl PartialEq for Order { 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(); } } } impl Market { fn exercise(&mut self) { let mut rng: StdRng=StdRng::seed_from_u64(13u64); let teppy=self.register_trader("Teppy"); let luni =self.register_trader("Luni"); let usd =self.register_asset("USD").unwrap(); let btc =self.register_asset("BTC").unwrap(); self.add_trader_balance(teppy,btc,100000.into()); self.add_trader_balance(luni ,usd,650000000.into()); let mut count=0; let mut tries=0; for _i in 1..=1000000 { let seller=if rng.gen_bool(0.5) { teppy } else { luni }; let (buy_type,sell_type,buy_qty,sell_qty):(usize,usize,FiNum,FiNum); if rng.gen_bool(0.5) { sell_type=btc; buy_type=usd; sell_qty=rng.gen_range(1..=5).into(); buy_qty=sell_qty*rng.gen_range(60..=70).into(); } else { sell_type=usd; buy_type=btc; buy_qty=rng.gen_range(1..=5).into(); sell_qty=buy_qty*rng.gen_range(60..=70).into(); } let mut _success=false; if self.make_order(seller,sell_type,buy_type,sell_qty,buy_qty) { count+=1; _success=true; }; if count>=1000000 { break; } tries+=1; } println!("Tries: {} Trades: {}",tries,count); self.sanity_check(); } } fn wt_level(index:usize) -> usize { (index^(index+1)).trailing_ones() as usize-1 } fn wt_leaf(index:usize) -> bool { index&1==0 } fn wt_left(index:usize) -> Option { let level=wt_level(index); if level>0 { Some(index-(1<<(wt_level(index)-1))) } else { None } } fn wt_right_edge(index: usize, edge: usize) -> Option { // Less than edge if index&1==0 { None } else { let mut r=wt_right(index).unwrap(); if r Option { let level=wt_level(index); if level>0 { Some(index+(1<<(wt_level(index)-1))) } else { None } } fn wt_parent(index:usize) -> usize { let lev=wt_level(index); let first_in_row=index%(1<>1; first_in_parent_row+nth_in_parent_row*skip_in_parent_row } fn wt_forefather(max_index:usize) -> usize { let mut rval=max_index; rval=rval|(rval>>1); rval=rval|(rval>>2); rval=rval|(rval>>4); rval=rval|(rval>>8); rval=rval|(rval>>16); rval=rval|(rval>>32); if rval>max_index { wt_left(rval).unwrap() } else { rval } } fn tree_stuff() { for i in (0..=60).step_by(1) { println!("Index {} Forefather {} Parent {}",i,wt_forefather(i),wt_parent(i)); } } fn royalty_stuff() { let mut rt=RoyaltyTree::new(); for index in 0..10 { rt.add_weight(index,FiNum::new_i32(10)); rt.add_royalty(FiNum::new_i32(24)) } for index in 0..rt.tree.len() { println!("Index: {} Weight_here {} Weight_below {} Weight_here_below {}",index,rt.weight_here(index),rt.weight_below(index),rt.weight_here_below(index)); } } fn process_file(fname: &str) { println!("Processing file: {}",fname) } fn interactive(m: &mut Market) { println!("Trading interactively in Tuesday Markets (demo)"); let stdin = io::stdin(); let mut trader:usize=0; for line in stdin.lock().lines() { match line { Ok(input) => { let tokens: Vec<&str> = input.split_whitespace().collect(); match tokens.as_slice() { ["dump"] => m.dump(), ["login", username] => if let Some(t)=m.trader_name2num.get_mut(*username) { trader=*t; println!("Logged in as {}",m.traders[trader].name) } else { println!("Trader {} not found.",username) }, ["whoami" ] => { println!("Logged in as {}, id {}",m.traders[trader].name,trader ); } ["addtrader", username] => { let id=m.register_trader(username); println!("Added user {} as id {}",username,id); }, ["balances"] => { println!("Balances for trader {}",m.traders[trader].name); for (key,value) in &m.traders[trader].balances { println!(" {} {}",m.number_to_name(*key),value); } } ["addasset", assetname] => { if let Some(cur)=m.register_asset(assetname) { println!("Added asset {} ",m.number_to_name(cur)) } else { println!("Asset {} already exists.",assetname) } } ["addfunds", username, qty0, cur0 ] => { let id=m.trader_name2num.get(*username); let qty=FiNum::new_str(qty0); let cur=m.name_to_number(cur0); if id.is_none() { println!("Could not find trader {}",username); } else if qty.is_zero() { println!("Could not parse quantity {}",qty0) } else if cur.is_none() { println!("Could not find asset {}",cur0) } else { let id=*id.unwrap(); let cur=*cur.unwrap(); m.add_trader_balance(id,cur,qty); println!("Added {} {} to {}",qty,m.number_to_asset(cur).name,m.traders[id].name) } } ["order", qty0, cur0, qty1, cur1 ] => { let qty0=FiNum::new_str(qty0); let cur0=m.name_to_number(cur0); let qty1=FiNum::new_str(qty1); let cur1=m.name_to_number(cur1); if !qty0.is_zero() && cur0.is_some() && !qty1.is_zero() && cur1.is_some() { m.make_order(trader,*cur0.unwrap(),*cur1.unwrap(),qty0,qty1); } } ["quit"] => { break; } _ => println!("Invalid command. Please try again."), } } Err(error) => println!("Error reading input: {}", error), } } } fn erase(filename: &str) { // Stub function for erasing a file println!("Erasing file: {}", filename); } fn copy(source: &str, destination: &str) { // Stub function for copying a file println!("Copying file from {} to {}", source, destination); } fn main() { let args: Vec = env::args().collect(); let mode=if args.len()<=1 { "--interactive" } else { args[1].as_str() }; let mut m=Market::new(); // USD type is 1, EUR type is 2, BTC type is 10, ETH type is 11, zKN6FBdD SOL type is 12 match mode { "--interactive" => interactive(&mut m), "--exercise" => m.exercise(), "--treestuff" => tree_stuff(), "--royaltystuff" => royalty_stuff(), _ => println!("Unknown mode: {}",mode), } }