Merge branch 'main' of https://www.gnaut.com/team/lzf1
This commit is contained in:
187
src/main.rs
187
src/main.rs
@@ -1,8 +1,11 @@
|
|||||||
#![allow(unsafe_code)]
|
#![allow(unsafe_code)]
|
||||||
|
use std::env;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
use std::cmp::min;
|
use std::cmp::min;
|
||||||
|
use std::rc::Rc;
|
||||||
|
use std::ops::DerefMut;
|
||||||
|
use std::cell::RefCell;
|
||||||
use rand::prelude::*;
|
use rand::prelude::*;
|
||||||
use rand::rngs::StdRng;
|
use rand::rngs::StdRng;
|
||||||
use finum::FiNum;
|
use finum::FiNum;
|
||||||
@@ -34,7 +37,7 @@ impl Trader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
struct Offer {
|
struct Order {
|
||||||
sell_qty: FiNum,
|
sell_qty: FiNum,
|
||||||
sell_remain: FiNum,
|
sell_remain: FiNum,
|
||||||
buy_qty: FiNum,
|
buy_qty: FiNum,
|
||||||
@@ -53,21 +56,30 @@ impl Dumpable for i32 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Dumpable for Offer {
|
|
||||||
|
impl Dumpable for Rc<RefCell<Order>> {
|
||||||
|
fn dump(&self) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
impl Dumpable for Order {
|
||||||
fn dump(&self) {
|
fn dump(&self) {
|
||||||
println!("Giving {}/{} to get {}",self.sell_remain,self.sell_qty,self.buy_qty);
|
println!("Giving {}/{} to get {}",self.sell_remain,self.sell_qty,self.buy_qty);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
struct Market {
|
struct Market {
|
||||||
asset_name2num: HashMap<String,i32>,
|
asset_name2num: HashMap<String,i32>,
|
||||||
asset_num2name: HashMap<i32,String>,
|
asset_num2name: HashMap<i32,String>,
|
||||||
asset_count:i32,
|
asset_count:i32,
|
||||||
money_supply: HashMap<i32,FiNum>,
|
money_supply: HashMap<i32,FiNum>,
|
||||||
offers: HashMap<(i32,i32),PQueue<Offer>>,
|
|
||||||
traders: Vec<Trader>,
|
traders: Vec<Trader>,
|
||||||
trader_name2num: HashMap<String,i32>,
|
trader_name2num: HashMap<String,i32>,
|
||||||
|
orders: HashMap<(i32,i32),PQueue<Rc<RefCell<Order>>>>,
|
||||||
|
royalties: HashMap<i32,Vec<Rc<RefCell<Order>>>>, // Active orders that are accepting asset X. They receive royalties when someone makes an order to sell X
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Market {
|
impl Market {
|
||||||
@@ -77,23 +89,26 @@ impl Market {
|
|||||||
asset_num2name: HashMap::new(),
|
asset_num2name: HashMap::new(),
|
||||||
asset_count:0,
|
asset_count:0,
|
||||||
money_supply: HashMap::new(),
|
money_supply: HashMap::new(),
|
||||||
offers: HashMap::new(),
|
orders: HashMap::new(),
|
||||||
|
royalties: HashMap::new(),
|
||||||
traders: Vec::new(),
|
traders: Vec::new(),
|
||||||
trader_name2num: HashMap::new(),
|
trader_name2num: HashMap::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
fn distribute_royalty(&self, amount:FiNum) {
|
||||||
|
}
|
||||||
fn sanity_check(&self) {
|
fn sanity_check(&self) {
|
||||||
println!("Sanity Checking Market...");
|
println!("Sanity Checking Market...");
|
||||||
for (cur,amt) in self.money_supply.iter() {
|
for (cur,amt) in self.money_supply.iter() {
|
||||||
println!("Money Supply {}: {}",self.number_to_name(*cur),*amt);
|
println!("Money Supply {}: {}",self.number_to_name(*cur),*amt);
|
||||||
let mut acc_offers=FiNum::new(0);
|
let mut acc_orders=FiNum::new(0);
|
||||||
for (ac,pq) in &self.offers { if ac.0==*cur {
|
for (ac,pq) in &self.orders { if ac.0==*cur {
|
||||||
for off in &*pq.v { acc_offers+=off.sell_remain; }
|
for off in &*pq.v { acc_orders+=off.borrow().sell_remain; }
|
||||||
} }
|
} }
|
||||||
let mut acc_traders=FiNum::new(0);
|
let mut acc_traders=FiNum::new(0);
|
||||||
for t in &self.traders { acc_traders+=t.get_balance(*cur); }
|
for t in &self.traders { acc_traders+=t.get_balance(*cur); }
|
||||||
let acc=acc_offers+acc_traders;
|
let acc=acc_orders+acc_traders;
|
||||||
println!(" {}: Offers {} Traders {} Total {} Should Be {}",self.number_to_name(*cur),acc_offers,acc_traders,acc,*amt);
|
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
|
fn register_trader(&mut self, name:&str) -> i32 { // Add error checking for inserting a trader twice
|
||||||
@@ -132,11 +147,12 @@ impl Market {
|
|||||||
println!(" {}: {}",self.number_to_name(*cur),*bal)
|
println!(" {}: {}",self.number_to_name(*cur),*bal)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (ap,pq) in &self.offers {
|
for (ap,pq) in &self.orders {
|
||||||
println!("Offers selling {} to buy {}:",self.number_to_name(ap.0),self.number_to_name(ap.1));
|
println!("Orders selling {} to buy {}:",self.number_to_name(ap.0),self.number_to_name(ap.1));
|
||||||
let mut sorted=pq.v.clone();
|
let mut sorted=pq.v.clone();
|
||||||
sorted.sort_by(|a,b| (a.sell_qty/a.buy_qty).cmp(&(b.sell_qty/b.buy_qty)));
|
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() {
|
for off in sorted.iter() {
|
||||||
|
let off=off.borrow();
|
||||||
println!(" {} @ {} ({})",
|
println!(" {} @ {} ({})",
|
||||||
off.sell_remain, // off.buy_qty*off.sell_remain/off.sell_qty,
|
off.sell_remain, // off.buy_qty*off.sell_remain/off.sell_qty,
|
||||||
off.buy_qty/off.sell_qty,
|
off.buy_qty/off.sell_qty,
|
||||||
@@ -145,37 +161,34 @@ impl Market {
|
|||||||
pq.dump();
|
pq.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
|
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
|
||||||
{
|
{
|
||||||
let initial_balance=self.traders[owner as usize].get_balance(sell_type);
|
let initial_balance=self.traders[owner as usize].get_balance(sell_type);
|
||||||
if initial_balance<sell_qty_initial { return false; }
|
if initial_balance<sell_qty_initial { return false; }
|
||||||
// println!("INITIAL_BALANCE {} Selling {} {} to buy {} {}",initial_balance,sell_qty_initial,self.number_to_name(sell_type),buy_qty_initial,self.number_to_name(buy_type));
|
|
||||||
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);
|
||||||
while buy_qty>FiNum::new(0) && self.offers.contains_key(&ap) && self.offers.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 elt=&mut self.offers.get_mut(&ap).unwrap().v[0];
|
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_initial/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);
|
||||||
// println!("Transacting {} at {}/{}, not at {}/{}. Elt.sell_remain is {}",qty,elt.buy_qty,elt.sell_qty,sell_qty_initial,buy_qty_initial,elt.sell_remain);
|
|
||||||
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; // 1.8499*194623/2.9744
|
||||||
// println!("qty {} * elt.buy_qty {} / elt.sell_qty {} = pay_qty {} ",qty,elt.buy_qty,elt.sell_qty,pay_qty);
|
|
||||||
// println!("qty {} * elt.buy_qty {} = pay_qty {} ",qty,elt.buy_qty, qty*elt.buy_qty);
|
|
||||||
// println!("Pay_qty is {}. Buy_qty is now {}. Balance is {}",pay_qty,buy_qty,self.traders[owner as usize].get_balance(sell_type));
|
|
||||||
self.traders[owner as usize].sub_balance(sell_type,pay_qty);
|
self.traders[owner as usize].sub_balance(sell_type,pay_qty);
|
||||||
self.traders[owner as usize].add_balance(buy_type ,qty);
|
self.traders[owner as usize].add_balance(buy_type ,qty);
|
||||||
self.traders[elt.owner as usize].add_balance(sell_type,pay_qty);
|
self.traders[elt.owner as usize].add_balance(sell_type,pay_qty);
|
||||||
if elt.sell_remain==0.into() { self.offers.get_mut(&ap).unwrap().pop(); }
|
if elt.sell_remain==0.into() { 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.offers.get_mut(&ap) { self.offers.insert(ap,PQueue::new()); }
|
if let None=self.orders.get_mut(&ap) { self.orders.insert(ap,PQueue::new()); }
|
||||||
let bids=self.offers.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_initial*buy_qty/buy_qty_initial;
|
||||||
if sell_qty_remain>0.into() {
|
if sell_qty_remain>0.into() {
|
||||||
bids.insert(Offer { owner:owner, sell_qty:sell_qty_remain, sell_remain:sell_qty_remain, buy_qty:buy_qty } );
|
let neworder=Rc::new(RefCell::new(Order { owner:owner, sell_qty:sell_qty_remain, sell_remain:sell_qty_remain, buy_qty:buy_qty } ));
|
||||||
|
bids.insert(neworder);
|
||||||
self.traders[owner as usize].sub_balance(sell_type,sell_qty_remain);
|
self.traders[owner as usize].sub_balance(sell_type,sell_qty_remain);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -183,7 +196,7 @@ impl Market {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PartialOrd for Offer {
|
impl PartialOrd for Order {
|
||||||
fn partial_cmp(&self, other:&Self) -> Option<Ordering> {
|
fn partial_cmp(&self, other:&Self) -> Option<Ordering> {
|
||||||
let ord0=self .sell_qty/self .buy_qty;
|
let ord0=self .sell_qty/self .buy_qty;
|
||||||
let ord1=other.sell_qty/other.buy_qty;
|
let ord1=other.sell_qty/other.buy_qty;
|
||||||
@@ -193,7 +206,7 @@ impl PartialOrd for Offer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PartialEq for Offer {
|
impl PartialEq for Order {
|
||||||
fn eq(&self, other:&Self) -> bool {
|
fn eq(&self, other:&Self) -> bool {
|
||||||
let ord0=self .sell_qty/self .buy_qty;
|
let ord0=self .sell_qty/self .buy_qty;
|
||||||
let ord1=other.sell_qty/other.buy_qty;
|
let ord1=other.sell_qty/other.buy_qty;
|
||||||
@@ -260,41 +273,91 @@ impl<T: Dumpable + std::cmp::PartialOrd + std::fmt::Debug> PQueue<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 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(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:u64) -> u32 {
|
||||||
|
(index^(index+1)).trailing_ones()-1
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wt_left(index:u64) -> Option<u64> {
|
||||||
|
let level=wt_level(index);
|
||||||
|
if level>0 { Some(index-(1<<(wt_level(index)-1))) } else { None }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wt_right(index:u64) -> Option<u64> {
|
||||||
|
let level=wt_level(index);
|
||||||
|
if level>0 { Some(index+(1<<(wt_level(index)-1))) } else { None }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wt_parent(index:u64) -> u64 {
|
||||||
|
let lev=wt_level(index);
|
||||||
|
let first_in_row=index%(1<<lev);
|
||||||
|
let skip=2<<lev;
|
||||||
|
let nth_in_row=(index-first_in_row)/skip;
|
||||||
|
let first_in_parent_row=(2<<lev)-1;
|
||||||
|
let skip_in_parent_row=4<<lev;
|
||||||
|
let nth_in_parent_row=nth_in_row>>1;
|
||||||
|
first_in_parent_row+nth_in_parent_row*skip_in_parent_row
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wt_forefather(max_index:u64) -> u64 {
|
||||||
|
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 main() {
|
fn main() {
|
||||||
let mut rng: StdRng=StdRng::seed_from_u64(13u64);
|
let args: Vec<String> = env::args().collect();
|
||||||
let debug_index=100000000;
|
let mode=if args.len()<=1 { "--exercise" } 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, 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
|
||||||
let teppy=m.register_trader("Teppy");
|
match mode {
|
||||||
let luni =m.register_trader("Luni");
|
"--exercise" => m.exercise(),
|
||||||
let usd =m.register_asset("USD");
|
"--treestuff" => tree_stuff(),
|
||||||
let btc =m.register_asset("BTC");
|
_ => println!("Unknown mode: {}",mode),
|
||||||
m.add_trader_balance(teppy,btc,100000.into());
|
}
|
||||||
m.add_trader_balance(luni ,usd,650000000.into());
|
}
|
||||||
let mut count=0;
|
|
||||||
let mut tries=0;
|
|
||||||
for i in 1..=10000000 {
|
|
||||||
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(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 m.make_offer(seller,sell_type,buy_type,sell_qty,buy_qty) { count+=1; success=true; };
|
|
||||||
// println!("{} selling {} {} to buy {} {}, {}",seller,sell_qty,m.number_to_name(sell_type),buy_qty,m.number_to_name(buy_type),if success { "success" } else { "failure" });
|
|
||||||
if count>=1000000 { break; }
|
|
||||||
tries+=1;
|
|
||||||
}
|
|
||||||
println!("Tries: {} Trades: {}",tries,count);
|
|
||||||
// m.dump();
|
|
||||||
m.sanity_check();
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user