This commit is contained in:
2024-07-26 16:54:03 -04:00
parent 99d45b53c4
commit b7cea710e4
2 changed files with 697 additions and 113 deletions

116
src/finum.rs Normal file
View File

@@ -0,0 +1,116 @@
use std::ops::{Add, Sub, Mul, Div, AddAssign, SubAssign};
use std::cmp::Ordering;
#[derive(Debug, Copy, Clone)]
pub struct FiNum(u64);
impl FiNum {
pub fn new_str(s: &str) -> Self {
match s.parse::<f64>() {
Ok(n) => Self::new((n*4294967296.0) as u64),
Err(_e) => Self::zero(),
}
}
pub fn new(value: u64) -> Self {
FiNum(value)
}
pub fn new_i32(value: i32) -> Self {
FiNum((value as u64)<<32)
}
pub fn zero() -> Self {
FiNum(0u64)
}
pub fn is_zero(self) -> bool {
self.0==0
}
pub fn value(&self) -> u64 {
self.0
}
pub fn recip(&self) -> Self {
FiNum((0x8000000000000000u64/self.0)<<1)
}
pub fn serialize(&self) -> String {
format!("{:X}",self.0)
}
pub fn new_deserialize(s: &str) -> Self {
FiNum(u64::from_str_radix(s, 16).unwrap())
}
}
impl From<i32> for FiNum {
fn from(value:i32) -> Self {
FiNum::new((value as u64)<<32)
}
}
impl PartialEq for FiNum {
fn eq(&self, other:&Self) -> bool {
self.0==other.0
}
}
impl Eq for FiNum { }
impl PartialOrd for FiNum {
fn partial_cmp(&self, other:&Self) -> Option<Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl Ord for FiNum {
fn cmp(&self, other:&Self) -> Ordering {
self.0.cmp(&other.0)
}
}
impl Add for FiNum {
type Output=Self;
fn add(self, other: Self) -> Self {
FiNum(self.0+other.0)
}
}
impl AddAssign for FiNum {
fn add_assign(&mut self, other: Self) {
self.0+=other.0;
}
}
impl Sub for FiNum {
type Output=Self;
fn sub(self, other: Self) -> Self {
FiNum(self.0-other.0)
}
}
impl SubAssign for FiNum {
fn sub_assign(&mut self, other: Self) {
self.0-=other.0;
}
}
impl Mul for FiNum {
type Output=Self;
fn mul(self, other: Self) -> Self {
FiNum(((self.value() as u128)*(other.value() as u128)>>32) as u64)
}
}
impl Div for FiNum {
type Output=Self;
fn div(self,other:Self) -> Self {
let ip=(self.value() as u128)/(other.value() as u128);
let rp=(self.value() as u128)%(other.value() as u128);
let fp=(rp<<32)/(other.value() as u128);
FiNum(((ip<<32)|fp) as u64)
}
}
impl std::fmt::Display for FiNum {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:.8}", (self.0 as f64)/((1u64<<32) as f64))
}
}

View File

@@ -5,12 +5,42 @@
// new node. // new node.
// //
// Case to think about: // Case to think about:
// Selling 140000 USD to buy 2 BTC. Weight is ===140k USD // Selling 140000 USD to buy 2 BTC. Weight is ===140k UShyucfdD
// Selling 50000 GBP to buy 1 BTC. Weight is === 50k GBP // Selling 50000 GBP to buy 1 BTC. Weight is === 50k GBP
// //
// Quick & Dirty Documentation
//
// Running lzf1 from a command line:
// lzf1 # --Interactive is the default mode, no need to
// lzf1 --log tuesday.log # Same as above, but log all commands to file tuesday.log
// lzf1 --replay tuesday.log # Replay tuesday.log, then go into interactive mode
// lzf1 --replay tuesday.log --log wednesday.log # Replay tuesday.log, then go interactive logging additional commands to wednesday.log
// lzf1 --replay tuesday.log --log tuesday.log # Replay tuesday.log, then go interactive, then append additional commands to tuesday.log
// Commands in Interactive Mode:
// addasset USD # Case sensitive, no spaces
// setroyalty USD 0.01 0.00 0.03 0.02 # Sets 1% royalty when order selling USD is placed, but no commission.
// # Then additional 3% royalty when order executes, plus 2% commission
// addtrader Teppy # Case sensitive, no spaces
// addfunds Teppy 20000 USD # Create funds from thin air. Do this when we receive a wire transfer, for instance.
// subfunds Teppy 0.5 BTC # Remove funds. Do this when we process a withdrawal.
// balances Teppy # Show all of Teppy's funds (but not what has been moved to the market)
// login Teppy # Some commands take an implicit Trader parameter. This sets that parameter
// whoami # Shows logged in name for this Interactive session
// wallet # Show all of the logged-in trader's funds (but not what is on the market)
// order 0.5 BTC 30000 USD # Create an order selling 0.5 BTC to buy 30000 USD. Uses logged in Trader's balance.
// quit # Clean exit
//
//
#![allow(unsafe_code)] #![allow(unsafe_code)]
#![allow(unused_variables)] #![allow(unused_variables)]
#![allow(dead_code)] #![allow(dead_code)]
use std::fs::File;
use std::fs::OpenOptions;
use std::path::Path;
use std::io::{self, BufRead, Write};
use std::env; use std::env;
use std::collections::HashMap; use std::collections::HashMap;
use std::cmp::Ordering; use std::cmp::Ordering;
@@ -18,19 +48,43 @@ use std::rc::Rc;
use std::cell::RefCell; use std::cell::RefCell;
use rand::prelude::*; use rand::prelude::*;
use rand::rngs::StdRng; use rand::rngs::StdRng;
mod finum;
use finum::FiNum; use finum::FiNum;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct Trader { struct Trader {
name: String, name: String,
password: String, // hash(name..salt..password)
id: usize, id: usize,
balances: HashMap<usize,FiNum>, // Maps Currency to Amount balances: HashMap<usize,FiNum>, // 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 { impl Trader {
fn new(name:&str,id:usize) -> Self { fn new(name:&str,id:usize) -> Self {
Trader { Trader {
name: String::from(name), name: String::from(name),
password: String::from(""),
id: id, id: id,
balances: HashMap::new() balances: HashMap::new()
} }
@@ -51,77 +105,124 @@ struct Order {
sell_qty: FiNum, sell_qty: FiNum,
sell_remain: FiNum, sell_remain: FiNum,
buy_qty: FiNum, buy_qty: FiNum,
royalty_remain: FiNum, // Based on royalty1
commission_remain: FiNum, // Based on commission1
owner: usize, owner: usize,
rt_loc: usize, // Location in the Royalty Tree rt_loc: usize, // Location in the Royalty Tree
} }
struct RoyaltyTree { struct RoyaltyTree {
tree: Vec<Royalty>, tree: Vec<Royalty>,
} next_entry: usize,
spare_change: FiNum, // Waiting to be distributed
impl RoyaltyTree {
fn new() -> Self {
RoyaltyTree { tree:Vec::new() }
}
fn get_weight(&self, index:usize) -> FiNum {
println!("Get_weight {} self.tree.len() {} ",index,self.tree.len());
if index<self.tree.len() { self.tree[index].weight }
else {
let ff=wt_forefather(index);
let mut index=index;
while index!=ff {
if index<self.tree.len() { return self.tree[index].weight }
else { index=wt_parent(index) }
}
while index>=self.tree.len() { index=wt_left(index).unwrap() }
self.tree[index].weight
}
}
} }
struct Royalty { struct Royalty {
weight: FiNum, // Here and below weight: FiNum, // Here and below
acc: FiNum, // Here and Below lazy: FiNum, // To be distributed to here and to below based on weights
acc: FiNum, // Accumulated here
} }
impl Royalty { impl Royalty {
fn new(weight: FiNum) -> Self { fn new() -> Self {
Royalty { weight:weight, acc:FiNum::new(0u64) } Royalty { weight:FiNum::zero(), lazy:FiNum::zero(), acc:FiNum::zero() }
} }
} }
impl RoyaltyTree { impl RoyaltyTree {
fn insert(&mut self, weight: FiNum, royalty:FiNum) -> usize { fn new() -> Self {
let last=self.tree.len(); RoyaltyTree { tree:Vec::new(), next_entry:0, spare_change:FiNum::zero() }
let mut nweight=weight;
if let Some(left )=wt_left (last) { if left <self.tree.len() { nweight+=self.tree[left ].weight } }
if let Some(right)=wt_right(last) { if right<self.tree.len() { nweight+=self.tree[right].weight } }
self.tree.push(Royalty::new(nweight));
let forefather=wt_forefather(last);
let mut pivot=last;
while pivot!=forefather {
pivot=wt_parent(pivot);
if pivot<self.tree.len() { self.tree[pivot].weight+=weight }
} }
self.tree[forefather].acc+=royalty; fn weight_here_below(&self, index:usize) -> FiNum {
last self.tree[index].weight
} }
fn capture(&mut self, index:usize, weight: FiNum) -> FiNum { fn weight_below(&self, index: usize) -> FiNum {
let ff=wt_forefather(index); 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<ff1 {
ff0=wt_parent(ff0);
self.tree[ff0].weight=w;
}
}
else { self.expand_to(wt_forefather(index)*2); }
self.get_royalty(index); // Just for the side effect of capturing everything to this point
let mut index=index; let mut index=index;
let mut rval=FiNum::zero(); let ff=self.forefather();
loop { while index!=ff {
let cap=self.tree[index].acc*weight/self.tree[index].weight; self.tree[index].weight+=weight;
self.tree[index].weight-=weight; index=wt_parent(index);
self.tree[index].acc-=cap;
rval+=cap;
if index!=ff { index=wt_parent(index); } else { break; }
} }
rval self.tree[index].weight+=weight;
} }
fn dump(&self) { fn forefather(&self) -> usize {
wt_forefather(self.tree.len()-1)
}
fn dump(&mut self) {
for index in 0..self.tree.len() { for index in 0..self.tree.len() {
println!("Index {} Weight {}",index,self.tree[index].weight); 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);
} }
} }
} }
@@ -154,32 +255,29 @@ impl Dumpable for Order {
struct Market { struct Market {
asset_name2num: HashMap<String,usize>, asset_name2num: HashMap<String,usize>,
asset_num2name: HashMap<usize,String>, assets: Vec<Asset>,
asset_count:usize,
money_supply: HashMap<usize,FiNum>, money_supply: HashMap<usize,FiNum>,
traders: Vec<Trader>, traders: Vec<Trader>,
trader_name2num: HashMap<String,usize>, trader_name2num: HashMap<String,usize>,
orders: HashMap<(usize,usize),PQueue<Rc<RefCell<Order>>>>, orders: HashMap<(usize,usize),PQueue<Rc<RefCell<Order>>>>,
royalties: HashMap<usize,RoyaltyTree>, // Active orders that are accepting asset X. They receive royalties when someone makes an order to sell X royalties: HashMap<usize,RoyaltyTree>, // Active orders that are accepting asset X. They receive royalties when someone makes an order to sell X
royalty_rate: HashMap<usize,FiNum>,
} }
impl Market { impl Market {
fn new() -> Self { fn new() -> Self {
let mut rval=Market { let mut rval=Market {
asset_name2num: HashMap::new(), asset_name2num: HashMap::new(),
asset_num2name: HashMap::new(), assets: Vec::new(),
asset_count:0,
money_supply: HashMap::new(), money_supply: HashMap::new(),
orders: HashMap::new(),
royalties: HashMap::new(),
traders: Vec::new(), traders: Vec::new(),
trader_name2num: HashMap::new(), trader_name2num: HashMap::new(),
orders: HashMap::new(),
royalties: HashMap::new(),
royalty_rate: HashMap::new(),
}; };
rval.register_trader("*NONE*"); rval.register_trader("*HOUSE*");
rval rval
}
fn distribute_royalty(&self, amount:FiNum) {
} }
fn sanity_check(&self) { fn sanity_check(&self) {
println!("Sanity Checking Market..."); println!("Sanity Checking Market...");
@@ -202,26 +300,39 @@ impl Market {
rval rval
} }
// These are the only ways to get money into or out of the market. // These are the only ways to get money into or out of the market.
fn get_trader_balance(&self, who:usize, cur:usize) -> FiNum {
self.traders[who].get_balance(cur)
}
fn add_trader_balance(&mut self, who:usize, cur:usize, delta: FiNum) { fn add_trader_balance(&mut self, who:usize, cur:usize, delta: FiNum) {
self.traders[who as usize].add_balance(cur,delta); self.traders[who].add_balance(cur,delta);
*self.money_supply.get_mut(&cur).unwrap()+=delta; *self.money_supply.get_mut(&cur).unwrap()+=delta;
} }
fn sub_trader_balance(&mut self, who:usize, cur:usize, delta: FiNum) { fn sub_trader_balance(&mut self, who:usize, cur:usize, delta: FiNum) {
self.traders[who as usize].sub_balance(cur,delta); self.traders[who].sub_balance(cur,delta);
*self.money_supply.get_mut(&cur).unwrap()-=delta; *self.money_supply.get_mut(&cur).unwrap()-=delta;
} }
fn register_asset(&mut self, name:&str) -> usize { fn register_asset(&mut self, name:&str) -> Option<usize> {
self.asset_count+=1; if self.asset_name2num.contains_key(name) { return None }
self.asset_name2num.insert(String::from(name),self.asset_count); self.assets.push(Asset::new(name));
self.asset_num2name.insert(self.asset_count,String::from(name)); self.asset_name2num.insert(String::from(name),self.assets.len()-1);
self.money_supply.insert(self.asset_count,FiNum::new(0)); self.money_supply.insert(self.assets.len()-1,FiNum::new(0));
self.asset_count let rval=self.assets.len()-1;
Some(rval)
} }
fn name_to_number(&self, name:&str) -> usize { fn set_royalty(&mut self, n: usize, roy0: FiNum, com0: FiNum, roy1: FiNum, com1: FiNum) {
*self.asset_name2num.get(name).unwrap() self.assets[n].royalty0_rate =roy0;
self.assets[n].commission0_rate=com0;
self.assets[n].royalty1_rate =roy1;
self.assets[n].commission1_rate=com1;
} }
fn number_to_name(&self, num:usize) -> &str { fn number_to_asset(&self, n: usize) -> Asset {
&*self.asset_num2name.get(&num).unwrap() 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) { fn dump(&self) {
println!("Dumping Market:"); println!("Dumping Market:");
@@ -245,40 +356,96 @@ impl Market {
pq.dump(); 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 fn replay_file(&mut self, fname:&str) {
{ println!("Replaying {}",fname);
let initial_balance=self.traders[owner as usize].get_balance(sell_type); let f=File::open(Path::new(fname));
if initial_balance<sell_qty_initial { return false; } let reader=io::BufReader::new(f.unwrap());
for line in reader.lines() {
if let Ok(line) = line {
let cmd=Command::deserialize(line);
let res=self.execute(&cmd);
println!("{}",res.describe());
}
}
}
fn make_order(&mut self, owner:usize, sell_type:usize, buy_type:usize, sell_qty_initial:FiNum, buy_qty_initial:FiNum) -> Result {
let mut log:Vec<String>=Vec::new();
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_balance<sell_qty_plus { return Result::Error(format!("Funds not available")) }
let mut buy_qty=buy_qty_initial; let mut buy_qty=buy_qty_initial;
let ap=(buy_type,sell_type); let ap=(buy_type,sell_type);
let mut royalty_acc=FiNum::zero();
let mut commission_acc=FiNum::zero();
while buy_qty>FiNum::new(0) && self.orders.contains_key(&ap) && self.orders.get(&ap).unwrap().v.len()>0 { while buy_qty>FiNum::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(); let mut elt=(*(self.orders.get(&ap).unwrap().v[0].borrow())).clone();
if sell_qty_initial/buy_qty_initial>=elt.buy_qty/elt.sell_qty { // Transact at ask_rate 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); let qty=std::cmp::min(elt.sell_remain,buy_qty);
elt.sell_remain-=qty; elt.sell_remain-=qty;
buy_qty-=qty; buy_qty-=qty;
let pay_qty=qty*elt.buy_qty/elt.sell_qty; // 1.8499*194623/2.9744 let pay_qty=qty*elt.buy_qty/elt.sell_qty;
self.traders[owner as usize].sub_balance(sell_type,pay_qty); self.traders[owner ].sub_balance(sell_type,pay_qty);
self.traders[owner as usize].add_balance(buy_type ,qty); self.traders[owner ].add_balance(buy_type ,qty);
self.traders[elt.owner as usize].add_balance(sell_type,pay_qty); self.traders[elt.owner].add_balance(sell_type,pay_qty);
if elt.sell_remain==0.into() { self.orders.get_mut(&ap).unwrap().pop(); } log.push(format!("Sold {} {} ({}) to buy {} {} ({})",pay_qty,self.number_to_name(sell_type),self.traders[owner ].name,
else { self.orders.get(&ap).unwrap().v[0].borrow_mut().sell_remain-=qty; } qty ,self.number_to_name(buy_type ),self.traders[elt.owner].name));
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;
println!("Transact at ask rate. Qty={} elt.sell_remain={} elt.royalty_remain={} elt.commission_remain={}",qty,elt.sell_remain,elt.royalty_remain,elt.commission_remain);
let rq2=if !elt.sell_remain.is_zero() { elt.royalty_remain *qty/elt.sell_remain } else { FiNum::zero() };
let cq2=if !elt.sell_remain.is_zero() { elt.commission_remain*qty/elt.sell_remain } else { FiNum::zero() };
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; } } else { break; }
} }
if buy_qty>0.into() { if buy_qty>0.into() {
let ap=(sell_type,buy_type); let ap=(sell_type,buy_type);
if let None=self.orders.get_mut(&ap) { self.orders.insert(ap,PQueue::new()); } if let None=self.orders.get_mut(&ap) { self.orders.insert(ap,PQueue::new()); }
let bids=self.orders.get_mut(&ap).unwrap(); let bids=self.orders.get_mut(&ap).unwrap();
let sell_qty_remain=sell_qty_initial*buy_qty/buy_qty_initial; let sell_qty_remain=sell_qty*buy_qty/buy_qty_initial;
if sell_qty_remain>0.into() { if sell_qty_remain>0.into() {
let rt_loc=self.royalties.entry(sell_type).or_insert(RoyaltyTree::new()).insert(sell_qty_remain,FiNum::zero()); 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( 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_loc } )); 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); bids.insert(neworder);
self.traders[owner as usize].sub_balance(sell_type,sell_qty_remain); self.traders[owner].sub_balance(sell_type,sell_qty_remain);
self.traders[0].add_balance(sell_type,commission0_qty);
log.push(format!("Moved {} {} ({}) to market",sell_qty_remain,self.number_to_name(sell_type),self.traders[owner].name));
} }
} }
true self.traders[0].add_balance(sell_type,commission_acc);
self.traders[owner].sub_balance(sell_type,royalty_acc+commission_acc);
log.push(format!("Paid {} {} in royalties and {} {} ({}) in commissions",royalty_acc ,self.number_to_name(sell_type),
commission_acc,self.number_to_name(sell_type),self.traders[owner].name));
Result::PlacedOrder(0,log)
} }
} }
@@ -364,8 +531,8 @@ impl Market {
let mut rng: StdRng=StdRng::seed_from_u64(13u64); let mut rng: StdRng=StdRng::seed_from_u64(13u64);
let teppy=self.register_trader("Teppy"); let teppy=self.register_trader("Teppy");
let luni =self.register_trader("Luni"); let luni =self.register_trader("Luni");
let usd =self.register_asset("USD"); let usd =self.register_asset("USD").unwrap();
let btc =self.register_asset("BTC"); let btc =self.register_asset("BTC").unwrap();
self.add_trader_balance(teppy,btc,100000.into()); self.add_trader_balance(teppy,btc,100000.into());
self.add_trader_balance(luni ,usd,650000000.into()); self.add_trader_balance(luni ,usd,650000000.into());
let mut count=0; let mut count=0;
@@ -385,7 +552,7 @@ impl Market {
sell_qty=buy_qty*rng.gen_range(60..=70).into(); sell_qty=buy_qty*rng.gen_range(60..=70).into();
} }
let mut _success=false; let mut _success=false;
if self.make_order(seller,sell_type,buy_type,sell_qty,buy_qty) { count+=1; _success=true; }; if let Result::Ok=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; tries+=1;
} }
@@ -407,6 +574,21 @@ fn wt_left(index:usize) -> Option<usize> {
if level>0 { Some(index-(1<<(wt_level(index)-1))) } else { None } if level>0 { Some(index-(1<<(wt_level(index)-1))) } else { None }
} }
fn wt_right_edge(index: usize, edge: usize) -> Option<usize> { // Less than edge
if index&1==0 { None }
else {
let mut r=wt_right(index).unwrap();
if r<edge { Some(r) }
else {
while r&1==1 {
if r<edge { return Some(r); }
else { r=wt_left(r).unwrap(); }
}
if r<edge { Some(r) } else { None }
}
}
}
fn wt_right(index:usize) -> Option<usize> { fn wt_right(index:usize) -> Option<usize> {
let level=wt_level(index); let level=wt_level(index);
if level>0 { Some(index+(1<<(wt_level(index)-1))) } else { None } if level>0 { Some(index+(1<<(wt_level(index)-1))) } else { None }
@@ -434,31 +616,317 @@ fn wt_forefather(max_index:usize) -> usize {
if rval>max_index { wt_left(rval).unwrap() } else { rval } 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() { fn royalty_stuff() {
let mut rt=RoyaltyTree::new(); let mut rt=RoyaltyTree::new();
for _ in 0..20 { for index in 0..10 {
rt.insert(FiNum::new_i32(10),FiNum::zero()); rt.add_weight(index,FiNum::new_i32(10));
rt.add_royalty(FiNum::new_i32(24))
} }
for index in 0..rt.tree.len() { for index in 0..rt.tree.len() {
println!("Index: {} Royalty: {}",index,rt.tree[index].weight); 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)
}
enum Result {
AddedTrader(usize),
AddedAsset(usize),
PlacedOrder(usize, Vec<String>),
FundsRemaining(FiNum),
Error(String),
Ok
}
enum Command {
AddTrader { user: String },
AddAsset { asset: String },
SetRoyalty { asset_id: usize, roy0: FiNum, com0: FiNum, roy1: FiNum, com1: FiNum },
AddFunds { user_id: usize, asset_id: usize, amt: FiNum },
SubFunds { user_id: usize, asset_id: usize, amt: FiNum },
Order { user_id: usize, sell_type: usize, sell_qty: FiNum, buy_type: usize, buy_qty: FiNum },
Retract { order_id: usize },
Error(String),
NOP(String),
None,
}
fn clean(s: &str) -> String { s.to_string() }
impl Command {
fn serialize(&self) -> String {
match self {
Self::AddTrader { user: name } => format!("AT {}",name),
Self::AddAsset { asset: name } => format!("AA {}",name),
Self::SetRoyalty { asset_id, roy0, com0 , roy1 , com1 }
=> format!("SR {} {} {} {} {}",asset_id,roy0.serialize(),com0.serialize(),roy1.serialize(),com1.serialize()),
Self::AddFunds { user_id, asset_id, amt }
=> format!("AF {} {} {}",user_id,asset_id,amt.serialize()),
Self::SubFunds { user_id, asset_id , amt }
=> format!("SF {} {} {}",user_id,asset_id,amt.serialize()),
Self::Order { user_id, sell_type, sell_qty, buy_type, buy_qty }
=> format!("OR {} {} {} {} {}",user_id,sell_type,sell_qty.serialize(),buy_type,buy_qty.serialize()),
Self::Retract { order_id } => format!("RE {}",order_id),
Self::NOP(str) => format!("NOP: {}",clean(str)),
_ => format!("NOP"),
}
}
fn deserialize(line: String) -> Self {
let tokens: Vec<&str> = line.split_whitespace().collect();
match tokens.as_slice() {
["AT",name] => Self::AddTrader { user: name.to_string() },
["AA",name] => Self::AddAsset { asset: name.to_string() },
["SR",asset_id,roy0,com0,roy1,com1] =>
Self::SetRoyalty { asset_id: asset_id.parse::<usize>().unwrap(), roy0: FiNum::new_deserialize(roy0), com0: FiNum::new_deserialize(com0),
roy1: FiNum::new_deserialize(roy1), com1: FiNum::new_deserialize(com1) },
["AF",user_id,asset_id,amt] =>
Self::AddFunds { user_id: user_id.parse::<usize>().unwrap(), asset_id: asset_id.parse::<usize>().unwrap(), amt: FiNum::new_deserialize(amt) },
["SF",user_id,asset_id,amt] =>
Self::SubFunds { user_id: user_id.parse::<usize>().unwrap(), asset_id: asset_id.parse::<usize>().unwrap(), amt: FiNum::new_deserialize(amt) },
["OR",user_id,sell_type,sell_qty,buy_type,buy_qty] =>
Self::Order { user_id: user_id.parse::<usize>().unwrap(), sell_type: sell_type.parse::<usize>().unwrap(), sell_qty: FiNum::new_deserialize(sell_qty),
buy_type: buy_type.parse::<usize>().unwrap(), buy_qty: FiNum::new_deserialize(buy_qty) },
["NOP", many_things @ ..] => Self::NOP(clean(&line)),
_ => Self::Error("Unimplemented Parse".to_string()),
}
}
}
impl Result {
fn describe(&self) -> String {
match self {
Self::PlacedOrder(order_id,vec) => format!("Placed order {}:\n {}",order_id,vec.join("\n ")),
Self::AddedTrader(id) => format!("Added Trader Id {}",id),
Self::AddedAsset(id) => format!("Added Asset Id {}",id),
Self::FundsRemaining(amt) => format!("Funds Remaining: {}",amt),
Self::Ok => format!("Ok"),
Self::Error(str) => format!("Error: {}",str),
// _ => "Some other result".to_string(),
}
}
fn print(&self) -> &Self {
println!("{}",self.describe());
self
}
}
impl Market {
fn execute(&mut self, cmd: &Command) -> Result {
match cmd {
Command::AddTrader { user: user_name } => {
let id=self.register_trader(user_name);
Result::AddedTrader(id)
}
Command::AddAsset { asset: asset_name } => {
if let Some(cur)=self.register_asset(asset_name) {
Result::AddedAsset(cur)
} else { Result::Error(format!("Asset {} already exists.",asset_name)) }
}
Command::SetRoyalty { asset_id,roy0,com0,roy1,com1 } => {
if *roy0+*com0+*roy1+*com1<FiNum::new_i32(1) {
self.set_royalty(*asset_id,*roy0,*com0,*roy1,*com1);
println!("Set royalty for {} to {} {} {} {}",asset_id,roy0,com0,roy1,com1);
Result::Ok
}
else { Result::Error(format!("Sum of royalties and commissions should be less than 1.00")) }
}
Command::AddFunds{ user_id, asset_id, amt } => {
self.add_trader_balance(*user_id,*asset_id,*amt);
println!("Added {} {} to {}",*amt,self.number_to_asset(*asset_id).name,self.traders[*user_id].name);
Result::FundsRemaining(self.get_trader_balance(*user_id,*asset_id))
}
Command::SubFunds { user_id,asset_id,amt } => {
if *amt>self.get_trader_balance(*user_id,*asset_id) { Result::Error(format!("Not enough {} in {}",asset_id,user_id)) }
else {
self.sub_trader_balance(*user_id,*asset_id,*amt);
println!("Subtracted {} {} from {}",*amt,self.number_to_asset(*asset_id).name,self.traders[*user_id].name);
Result::FundsRemaining(self.get_trader_balance(*user_id,*asset_id))
}
}
Command::Order { user_id, sell_type, sell_qty, buy_type, buy_qty } => {
self.make_order(*user_id,*sell_type,*buy_type,*sell_qty,*buy_qty)
}
Command::Error(str) => Result::Error(format!("Command Error")),
Command::NOP(str) => Result::Ok,
_ => Result::Error(format!("Tried to execute an unimplemented Command. This is a bug because all Commands should be implemented, even NOPs and Errors.")),
}
} }
} }
fn tokens_to_command(m: &Market, logged_in: usize, tokens: Vec<&str>) -> Command {
let cmd:Command=match &tokens[..] {
["addtrader", username] => Command::AddTrader { user: username.to_string() },
["addasset", assetname] => Command::AddAsset { asset: assetname.to_string() },
["setroyalty", assetname, roy0, com0, roy1, com1] => {
if let Some(cur)=m.name_to_number(assetname) {
let roy0=FiNum::new_str(roy0);
let com0=FiNum::new_str(com0);
let roy1=FiNum::new_str(roy1);
let com1=FiNum::new_str(com1);
if roy0+com0+roy1+com1<FiNum::new_i32(1) {
Command::SetRoyalty { asset_id: *cur, roy0: roy0, com0: com0, roy1: roy1, com1: com1 }
} else { Command::Error("Sum of royalties must be less than 1".to_string()) }
} else {
Command::Error("Unknown Asset".to_string())
}
}
["addfunds", username, qty0, cur0 ] => {
let user=m.trader_name2num.get(*username);
let qty=FiNum::new_str(qty0);
let cur=m.name_to_number(cur0);
if user.is_none() { Command::Error(format!("Could not find trader {}",username)) }
else if qty.is_zero() { Command::Error(format!("Could not parse quantity {}",qty0)) }
else if cur.is_none() { Command::Error(format!("Could not find asset {}",cur0)) }
else {
let user=*user.unwrap();
let cur=*cur.unwrap();
Command::AddFunds { user_id: user, asset_id: cur, amt: qty }
}
}
["subfunds", username, qty0, cur0 ] => {
let user=m.trader_name2num.get(*username);
let qty=FiNum::new_str(qty0);
let cur=m.name_to_number(cur0);
if user.is_none() { Command::Error(format!("Could not find trader {}",username)) }
else if qty.is_zero() { Command::Error(format!("Could not parse quantity {}",qty0)) }
else if cur.is_none() { Command::Error(format!("Could not find asset {}",cur0)) }
else {
let user=*user.unwrap();
let cur=*cur.unwrap();
Command::SubFunds { user_id: user, asset_id: cur, amt: qty }
}
}
["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 !cur0.is_some() { Command::Error("Count not find currency".to_string()) }
else if !cur1.is_some() { Command::Error("Count not find currency".to_string()) }
else if qty0.is_zero() { Command::Error("Qty0 is must be > 0".to_string()) }
else if qty1.is_zero() { Command::Error("Qty1 is must be > 0".to_string()) }
else { Command::Order { user_id: logged_in, sell_type: *cur0.unwrap(), sell_qty: qty0, buy_type: *cur1.unwrap(), buy_qty: qty1 } }
}
_ => { Command::Error("Unknown Command".to_string()) },
};
cmd
}
fn interactive(m: &mut Market, mut out: Option<File>) {
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();
let cmd:Command=match tokens.as_slice() {
["dump"] => { m.dump(); Command::None },
["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) }
Command::None
},
["whoami" ] => { println!("Logged in as {}, id {}",m.traders[trader].name,trader ); Command::None }
["wallet"] => {
for (key,value) in &m.traders[trader].balances { println!(" {} {}",m.number_to_name(*key),value); }
Command::None
}
["balances", username] => {
if let Some(user)=m.trader_name2num.get(*username) {
println!("Balances for trader {}",m.traders[*user].name);
for (key,value) in &m.traders[*user].balances { println!(" {} {}",m.number_to_name(*key),value); }
} else { println!("Could not find trader {}",username); }
Command::None
},
["quit"] => { return },
_ => {
let cmd=tokens_to_command(m,trader,tokens);
if let Some(ref mut f)=out {
let ser=cmd.serialize();
if let Err(e)=writeln!(f,"{}",ser) { eprintln!("An error occurred while writing {}",e); }
else { println!("Wrote to logfile: {}",ser); }
}
let res=m.execute(&cmd);
println!("Result: {}",res.describe());
Command::None
},
};
}
Err(error) => println!("Error reading input: {}", error),
}
}
}
fn numbers_stuff() {
println!("Numbers_stuff");
let n=FiNum::new_i32(7)/FiNum::new_i32(2);
let n_s=n.serialize();
let n_d=FiNum::new_deserialize(&n_s);
println!("N is {}, Serialized to {}, Deserialized to {}",n,n_s,n_d);
}
fn paths_match(path0: &str, path1: &str) -> bool
{
let path0 = Path::new(path0);
let path1 = Path::new(path1);
path0 == path1
}
//
// Use cases:
// Replace logfile
// Replay logfile and then append to it
// Replay one logfile and then replace a different one
// Future additional use cases:
// Replay logfile1+logfile2+... and then replace a different log file
// Replay logfile1+logfile2+logfileN and then append to logfileN
//
fn main() { fn main() {
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
let mode=if args.len()<=1 { "--exercise" } else { args[1].as_str() }; let mut options:HashMap<&str,String>=HashMap::new();
let mut i=1;
enum Mode { Help, Royalty, Interactive, Exercise, Numbers, None }
let mut mode_count=0;
let mut mode=Mode::None;
while i<args.len() {
match args[i].as_str() {
"--help" => { mode=Mode::Help; mode_count+=1; i+=1; }
"--interactive" => { mode=Mode::Interactive; mode_count+=1; i+=1; }
"--royalty" => { mode=Mode::Royalty; mode_count+=1; i+=1; }
"--exercise" => { mode=Mode::Exercise; mode_count+=1; i+=1; }
"--numbers" => { mode=Mode::Numbers; mode_count+=1; i+=1; }
"--log" => {
if i+1>=args.len() { println!("No log file specified."); return; }
else { options.insert("logfile",args[i+1].clone()); i+=2; }
}
"--replay" => {
if i+1>=args.len() { println!("No replay file specified."); return; }
else { options.insert("replay",args[i+1].clone()); i+=2; }
}
_ => { println!("Unknown option."); return; }
}
}
if mode_count==0 { mode=Mode::Interactive; mode_count+=1; }
if mode_count!=1 { println!("You may only select one mode to run in."); return; }
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 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
if options.contains_key("replay") { m.replay_file(options.get("replay").unwrap()); }
match mode { match mode {
"--exercise" => m.exercise(), Mode::Interactive => {
"--treestuff" => tree_stuff(), if options.contains_key("logfile") {
"--royaltystuff" => royalty_stuff(), let ap=options.contains_key("replay") && paths_match(options.get("replay").unwrap(),options.get("logfile").unwrap());
_ => println!("Unknown mode: {}",mode), let f=OpenOptions::new().write(true).append(ap).truncate(!ap).create(true).open(options.get("logfile").unwrap());
if let Ok(f)=f { interactive(&mut m,Some(f)); }
else { println!("Could not open logfile for writing."); }
} else { interactive(&mut m,None); }
}
Mode::Exercise => m.exercise(),
Mode::Numbers => numbers_stuff(),
Mode::Royalty => royalty_stuff(),
_ => println!("Unspecified mode"),
} }
} }