diff --git a/src/main.rs b/src/main.rs index 125549d..b5302a7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,20 @@ +// +// 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::env; use std::collections::HashMap; use std::cmp::Ordering; -use std::cmp::min; use std::rc::Rc; -use std::ops::DerefMut; use std::cell::RefCell; use rand::prelude::*; use rand::rngs::StdRng; @@ -13,25 +23,25 @@ use finum::FiNum; #[derive(Debug, Clone)] struct Trader { name: String, - id: i32, - balances: HashMap, // Maps Currency to Amount + id: usize, + balances: HashMap, // Maps Currency to Amount } impl Trader { - fn new(name:&str,id:i32) -> Self { + fn new(name:&str,id:usize) -> Self { Trader { name: String::from(name), id: id, balances: HashMap::new() } } - fn add_balance(&mut self, cur:i32, delta:FiNum) { + 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:i32, delta:FiNum) { + fn sub_balance(&mut self, cur:usize, delta:FiNum) { self.balances.entry(cur).and_modify(|ent| *ent-=delta ); } - fn get_balance(&self, cur:i32) -> FiNum { + fn get_balance(&self, cur:usize) -> FiNum { *self.balances.get(&cur).map(|bal| bal).unwrap_or(&FiNum::new(0u64)) } } @@ -41,16 +51,132 @@ struct Order { sell_qty: FiNum, sell_remain: FiNum, buy_qty: FiNum, - royalty_acc: FiNum, // Buy type. In the royalty tree, for this node and those to the left - royalty_cap: FiNum, // In the royalty tree, just for this node. - owner: i32, + owner: usize, + rt_loc: usize, // Location in the Royalty Tree } +struct RoyaltyTree { + tree: Vec, + next_entry: usize, + } + +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 } + } + 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); + println!("Weight_here at {}, weight_here_below {}, weight_below {}",index,w0,w1); + w0-w1 + } + } + fn expand_to(&mut self, index: usize) -> &mut Self { + println!("Expand_to {} ",index); + for _ in self.tree.len()..=index { println!(" Push!"); 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=lazy*self.weight_here(index)/self.weight_here_below(index); + let d02=lazy-d1; + let index_left =wt_left (index).unwrap(); + let index_right=wt_right(index).unwrap(); + let d0=d02*self.weight_here_below(index_left)/self.weight_below(index); + 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) { + let ff=self.forefather(); + self.tree[ff].lazy+=amount; + println!("Add royalty amount {}, storing at node {}, lazy amount there is now {}",amount,ff,self.tree[ff].lazy); + } + fn add_weight(&mut self, index: usize, weight: FiNum) { + println!("Add_weight at {}",index); + if self.tree.len()>0 { + let mut ff0=self.forefather(); + self.expand_to(wt_forefather(index)*2); + let ff=self.forefather(); + while ff0!=ff { + let w=self.tree[ff0].weight; + ff0=wt_parent(ff0); + self.tree[ff0].weight=w; + } + } + let ff=self.forefather(); + self.get_royalty(index); // Just for the side effect of capturing everything to this point + let mut index=index; + println!("Ascending from {} to {}",index,ff); + while index!=ff { + self.tree[index].weight+=weight; + index=wt_parent(index); + } + self.tree[index].weight+=weight; + } + fn forefather(&self) -> 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 i32 { +impl Dumpable for usize { fn dump(&self) { println!("Dump Integer: {}",self); } @@ -72,30 +198,33 @@ impl Dumpable for Order { struct Market { - asset_name2num: HashMap, - asset_num2name: HashMap, - asset_count:i32, - money_supply: HashMap, + asset_name2num: HashMap, + asset_num2name: HashMap, + asset_count:usize, + money_supply: HashMap, traders: Vec, - trader_name2num: HashMap, - orders: HashMap<(i32,i32),PQueue>>>, - royalties: HashMap>>>, // Active orders that are accepting asset X. They receive royalties when someone makes an order to sell X + 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 } impl Market { fn new() -> Self { - Market { + let mut rval=Market { asset_name2num: HashMap::new(), asset_num2name: HashMap::new(), asset_count:0, money_supply: HashMap::new(), orders: HashMap::new(), - royalties: HashMap::new(), + royalties: HashMap::new(), traders: Vec::new(), trader_name2num: HashMap::new(), - } + }; + rval.register_trader("*NONE*"); + rval } fn distribute_royalty(&self, amount:FiNum) { + } fn sanity_check(&self) { println!("Sanity Checking Market..."); @@ -111,32 +240,32 @@ impl Market { println!(" {}: Orders {} Traders {} Total {} Should Be {}",self.number_to_name(*cur),acc_orders,acc_traders,acc,*amt); } } - fn register_trader(&mut self, name:&str) -> i32 { // Add error checking for inserting a trader twice - let rval=self.traders.len() as i32; - self.trader_name2num.insert(String::from(name),self.traders.len() as i32); + 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:i32, cur:i32, delta: FiNum) { + 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:i32, cur:i32, delta: FiNum) { + 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) -> i32 { + fn register_asset(&mut self, name:&str) -> usize { 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.money_supply.insert(self.asset_count,FiNum::new(0)); self.asset_count } - fn name_to_number(&self, name:&str) -> i32 { + fn name_to_number(&self, name:&str) -> usize { *self.asset_name2num.get(name).unwrap() } - fn number_to_name(&self, num:i32) -> &str { + fn number_to_name(&self, num:usize) -> &str { &*self.asset_num2name.get(&num).unwrap() } fn dump(&self) { @@ -152,7 +281,7 @@ impl Market { 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(); + let off=off.borrow(); println!(" {} @ {} ({})", off.sell_remain, // off.buy_qty*off.sell_remain/off.sell_qty, off.buy_qty/off.sell_qty, @@ -161,7 +290,7 @@ impl Market { pq.dump(); } } - fn make_order(&mut self, owner:i32, sell_type:i32, buy_type:i32, sell_qty_initial:FiNum, buy_qty_initial:FiNum) -> bool // Dollars, Bitcoin, 64000, 1 + 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 as usize].get_balance(sell_type); if initial_balance0.into() { @@ -187,7 +316,10 @@ impl Market { let bids=self.orders.get_mut(&ap).unwrap(); let sell_qty_remain=sell_qty_initial*buy_qty/buy_qty_initial; if sell_qty_remain>0.into() { - let neworder=Rc::new(RefCell::new(Order { owner:owner, sell_qty:sell_qty_remain, sell_remain:sell_qty_remain, buy_qty:buy_qty } )); +// self.royalties.entry(sell_type).or_insert(RoyaltyTree::new()).insert(sell_qty_remain); +// let rt_loc=self.royalties.get(&sell_type).unwrap().tree.len(); + 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: 0 } )); bids.insert(neworder); self.traders[owner as usize].sub_balance(sell_type,sell_qty_remain); } @@ -276,17 +408,17 @@ impl PQueue { 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"); - let btc =self.register_asset("BTC"); - 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..=10000000 { + let teppy=self.register_trader("Teppy"); + let luni =self.register_trader("Luni"); + let usd =self.register_asset("USD"); + let btc =self.register_asset("BTC"); + 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):(i32,i32,FiNum,FiNum); + 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; @@ -300,7 +432,7 @@ impl Market { } 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; } + if count>=1000000 { break; } tries+=1; } println!("Tries: {} Trades: {}",tries,count); @@ -308,21 +440,40 @@ impl Market { } } -fn wt_level(index:u64) -> u32 { - (index^(index+1)).trailing_ones()-1 +fn wt_level(index:usize) -> usize { + (index^(index+1)).trailing_ones() as usize-1 } -fn wt_left(index:u64) -> Option { +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(index:u64) -> Option { +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:u64) -> u64 { +fn wt_parent(index:usize) -> usize { let lev=wt_level(index); let first_in_row=index%(1< u64 { first_in_parent_row+nth_in_parent_row*skip_in_parent_row } -fn wt_forefather(max_index:u64) -> u64 { +fn wt_forefather(max_index:usize) -> usize { let mut rval=max_index; rval=rval|(rval>>1); rval=rval|(rval>>2); @@ -347,7 +498,18 @@ fn wt_forefather(max_index:u64) -> u64 { 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..20 { + 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)); + } } @@ -357,7 +519,8 @@ fn main() { 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 { "--exercise" => m.exercise(), - "--treestuff" => tree_stuff(), - _ => println!("Unknown mode: {}",mode), - } + "--treestuff" => tree_stuff(), + "--royaltystuff" => royalty_stuff(), + _ => println!("Unknown mode: {}",mode), + } }