fuck man major readjustment but it is running again...
This commit is contained in:
Vendored
+5
-1
@@ -1,3 +1,7 @@
|
|||||||
{
|
{
|
||||||
"ansible.python.interpreterPath": "c:\\Users\\handg\\miniconda3\\python.exe"
|
"ansible.python.interpreterPath": "c:\\Users\\handg\\miniconda3\\python.exe",
|
||||||
|
"[python]": {
|
||||||
|
"editor.defaultFormatter": "ms-python.autopep8"
|
||||||
|
},
|
||||||
|
"python.formatting.provider": "none"
|
||||||
}
|
}
|
||||||
+2
-2
@@ -4,7 +4,7 @@ spec:
|
|||||||
max_world_price: 100
|
max_world_price: 100
|
||||||
|
|
||||||
- name: "Food"
|
- name: "Food"
|
||||||
max_world_price: 10
|
max_world_price: 5
|
||||||
|
|
||||||
- name: "Grain"
|
- name: "Grain"
|
||||||
max_world_price: 5
|
max_world_price: 5
|
||||||
@@ -13,5 +13,5 @@ spec:
|
|||||||
max_world_price: 1
|
max_world_price: 1
|
||||||
|
|
||||||
- name: "Fruit"
|
- name: "Fruit"
|
||||||
max_world_price: 1
|
max_world_price: 5
|
||||||
|
|
||||||
+11
-11
@@ -2,29 +2,29 @@ kind: production
|
|||||||
spec:
|
spec:
|
||||||
|
|
||||||
- name: Grain
|
- name: Grain
|
||||||
amount: 100
|
amount: 1000
|
||||||
prod:
|
prod:
|
||||||
- Raw_Agriculture_Plot: 1
|
Raw_Agriculture_Plot: 1
|
||||||
- name: Fruit
|
- name: Fruit
|
||||||
amount: 75
|
amount: 1000
|
||||||
prod:
|
prod:
|
||||||
- Raw_Agriculture_Plot: 1
|
Raw_Agriculture_Plot: 1
|
||||||
- name: Wood
|
- name: Wood
|
||||||
amount: 10
|
amount: 1000
|
||||||
prod:
|
prod:
|
||||||
- Raw_Forrest: 1
|
Raw_Forrest: 1
|
||||||
|
|
||||||
- name: Fuel
|
- name: Fuel
|
||||||
amount: 10
|
amount: 10
|
||||||
prod:
|
prod:
|
||||||
- Wood: 1
|
Wood: 1
|
||||||
|
|
||||||
- name: Food
|
- name: Food
|
||||||
amount: 10
|
amount: 5
|
||||||
prod:
|
prod:
|
||||||
- Fuel: 1
|
Fuel: 1
|
||||||
- Fruit: 1
|
Fruit: 1
|
||||||
- Grain: 2
|
Grain: 2
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -5,7 +5,7 @@ class AutoProductionAgent(BaseAgent):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def __init__(self,sim,business,worker=1,employment_rate=0) -> None:
|
def __init__(self,sim,business,worker=-1,employment_rate=0) -> None:
|
||||||
super().__init__(sim)
|
super().__init__(sim)
|
||||||
self.business=business
|
self.business=business
|
||||||
self.prod=business.production
|
self.prod=business.production
|
||||||
@@ -13,32 +13,56 @@ class AutoProductionAgent(BaseAgent):
|
|||||||
self.employment_rate=employment_rate
|
self.employment_rate=employment_rate
|
||||||
self.employment_index=worker
|
self.employment_index=worker
|
||||||
self.target=0
|
self.target=0
|
||||||
|
self.prod_counter=0
|
||||||
|
|
||||||
def set_worker(self,workers):
|
def set_worker(self,workers):
|
||||||
if workers>1:
|
if workers>1:
|
||||||
self.worker=workers
|
self.worker=workers
|
||||||
|
elif workers==-1:
|
||||||
|
self.worker=-1
|
||||||
else:
|
else:
|
||||||
self.worker=1
|
self.worker=1
|
||||||
def set_target(self,qty):
|
def set_target(self,qty):
|
||||||
self.target=qty
|
self.target=qty
|
||||||
def can_produce(self):
|
def can_produce(self):
|
||||||
# If can produce item
|
# how much can we produce
|
||||||
for com in self.prod["prod"]:
|
minprod=[]
|
||||||
for k,v in com.items():
|
|
||||||
if v > self.business.inventory[k]:
|
for k,v in self.prod["prod"].items():
|
||||||
return False
|
minprod.append(self.business.inventory[k]/v)
|
||||||
|
possibleProds=int(min(minprod))
|
||||||
|
|
||||||
|
return possibleProds*self.prod["amount"]
|
||||||
|
|
||||||
|
def should_produce(self):
|
||||||
# check if we should produce
|
# check if we should produce
|
||||||
if self.business.resource_in_possesion()>self.target:
|
if self.business.resource_in_possesion()>=self.target:
|
||||||
return False
|
return 0
|
||||||
return True
|
|
||||||
|
return self.can_produce()
|
||||||
|
|
||||||
def tick(self,step,epi):
|
def tick(self,step,epi):
|
||||||
for i in range(self.worker):
|
can=self.should_produce()
|
||||||
if not self.can_produce():
|
if can==0:
|
||||||
continue
|
return
|
||||||
|
|
||||||
|
run=True
|
||||||
|
i=self.worker
|
||||||
|
while run:
|
||||||
|
if self.should_produce()==0:
|
||||||
|
return
|
||||||
|
if i==0:
|
||||||
|
return
|
||||||
# remove cost from inventory
|
# remove cost from inventory
|
||||||
for com in self.prod["prod"]:
|
|
||||||
for k,cost in com.items():
|
for k,cost in self.prod["prod"].items():
|
||||||
self.business.inventory[k]-=cost
|
self.business.inventory[k]-=cost
|
||||||
# add commodity
|
# add commodity
|
||||||
self.business.inventory[self.prod['name']]+=self.prod["amount"]
|
self.business.inventory[self.prod['name']]+=self.prod["amount"]
|
||||||
|
self.prod_counter+=1
|
||||||
|
i-=1
|
||||||
|
|
||||||
|
def reset_qty(self):
|
||||||
|
self.prod_counter=0
|
||||||
|
def qty(self):
|
||||||
|
return self.prod_counter
|
||||||
@@ -17,6 +17,9 @@ class Base_Aquire_Agent(BaseAgent,ABC):
|
|||||||
self.orders={i: {} for i in range(len(self.exchanges))}
|
self.orders={i: {} for i in range(len(self.exchanges))}
|
||||||
self.target=0
|
self.target=0
|
||||||
self.trades=[]
|
self.trades=[]
|
||||||
|
self.tqty=0
|
||||||
|
self.qty_offset=0
|
||||||
|
self.expense=0
|
||||||
self.max_price=-1
|
self.max_price=-1
|
||||||
super().__init__(simulation)
|
super().__init__(simulation)
|
||||||
|
|
||||||
@@ -57,10 +60,11 @@ class Base_Aquire_Agent(BaseAgent,ABC):
|
|||||||
return None # we dont have enough balance
|
return None # we dont have enough balance
|
||||||
|
|
||||||
self.business.balance-=total_price
|
self.business.balance-=total_price
|
||||||
|
self.expense+=total_price
|
||||||
cx.add_to_account(self.id,"balance",total_price) # prepaid charge account for cx
|
cx.add_to_account(self.id,"balance",total_price) # prepaid charge account for cx
|
||||||
order=cx.submit_order(self.id,self.resource,amount,price_per,Side.BUY)
|
order=cx.submit_order(self.id,self.resource,amount,price_per,Side.BUY)
|
||||||
if order==None: # Order failed
|
if order==None: # Order failed
|
||||||
return False
|
return None
|
||||||
self.orders[cx_id][order.order_id]=order
|
self.orders[cx_id][order.order_id]=order
|
||||||
self.update_trades()
|
self.update_trades()
|
||||||
return order
|
return order
|
||||||
@@ -73,6 +77,7 @@ class Base_Aquire_Agent(BaseAgent,ABC):
|
|||||||
amount=cx.get_account_resource_amount(self.id,"balance")
|
amount=cx.get_account_resource_amount(self.id,"balance")
|
||||||
cx.remove_from_account(self.id,"balance",amount)
|
cx.remove_from_account(self.id,"balance",amount)
|
||||||
self.business.balance+=amount
|
self.business.balance+=amount
|
||||||
|
self.expense-=amount
|
||||||
|
|
||||||
def collect_resource_from_cxs(self,resource):
|
def collect_resource_from_cxs(self,resource):
|
||||||
"""
|
"""
|
||||||
@@ -88,13 +93,33 @@ class Base_Aquire_Agent(BaseAgent,ABC):
|
|||||||
Returns a list of all trades performed by this agent
|
Returns a list of all trades performed by this agent
|
||||||
"""
|
"""
|
||||||
trades=[]
|
trades=[]
|
||||||
|
self.tqty=0
|
||||||
for cx_id in range(len(self.exchanges)):
|
for cx_id in range(len(self.exchanges)):
|
||||||
cx=self.exchanges[cx_id]
|
cx=self.exchanges[cx_id]
|
||||||
orders=self.orders[cx_id]
|
orders=self.orders[cx_id]
|
||||||
if len(orders)>0:
|
if len(orders)>0:
|
||||||
for k,o in orders.items():
|
for k,o in orders.items():
|
||||||
if k in cx.order_trades_map:
|
if k in cx.order_trades_map:
|
||||||
trades.append(cx.order_trades_map[k])
|
trades.extend(cx.order_trades_map[k])
|
||||||
|
|
||||||
self.trades=trades
|
self.trades=trades
|
||||||
|
for t in trades:
|
||||||
|
self.tqty+=t.trade_qty
|
||||||
return trades
|
return trades
|
||||||
|
|
||||||
|
# Confirm a purchase of x amount to reduce qty and expense counter
|
||||||
|
def confirm_purchase(self,confirmed_qty):
|
||||||
|
expensePer=self.expense/self.qty
|
||||||
|
confirmedExpense=expensePer*confirmed_qty
|
||||||
|
self.expense-=confirmedExpense
|
||||||
|
self.qty_offset-=confirmed_qty
|
||||||
|
|
||||||
|
@property
|
||||||
|
def qty(self):
|
||||||
|
return self.tqty+self.qty_offset
|
||||||
|
|
||||||
|
def reset(self, episode):
|
||||||
|
#self.tqty=0
|
||||||
|
self.qty_offset=0
|
||||||
|
self.trades=[]
|
||||||
|
return super().reset(episode)
|
||||||
@@ -2,6 +2,7 @@ from .base_agent import BaseAgent
|
|||||||
from ..exchange import Exchange
|
from ..exchange import Exchange
|
||||||
from lightmatchingengine.lightmatchingengine import Order,Side
|
from lightmatchingengine.lightmatchingengine import Order,Side
|
||||||
from abc import ABC
|
from abc import ABC
|
||||||
|
from decimal import *
|
||||||
class Base_Distribution_Agent(BaseAgent,ABC):
|
class Base_Distribution_Agent(BaseAgent,ABC):
|
||||||
|
|
||||||
def __init__(self,simulation,business,resource,exchanges: list) -> None:
|
def __init__(self,simulation,business,resource,exchanges: list) -> None:
|
||||||
@@ -18,6 +19,10 @@ class Base_Distribution_Agent(BaseAgent,ABC):
|
|||||||
self.target=0
|
self.target=0
|
||||||
self.min_price=-1
|
self.min_price=-1
|
||||||
self.max_batch_qty=10
|
self.max_batch_qty=10
|
||||||
|
self.tincome=0
|
||||||
|
self.tqty=0
|
||||||
|
self.income_offset=0
|
||||||
|
self.qty_offset=0
|
||||||
super().__init__(simulation)
|
super().__init__(simulation)
|
||||||
|
|
||||||
def set_target(self,target: int):
|
def set_target(self,target: int):
|
||||||
@@ -57,6 +62,7 @@ class Base_Distribution_Agent(BaseAgent,ABC):
|
|||||||
return False # we dont have enough balance
|
return False # we dont have enough balance
|
||||||
|
|
||||||
self.business.inventory[self.resource]-=amount
|
self.business.inventory[self.resource]-=amount
|
||||||
|
|
||||||
cx.add_to_account(self.id,self.resource,amount) # prepaid charge account for cx
|
cx.add_to_account(self.id,self.resource,amount) # prepaid charge account for cx
|
||||||
order=cx.submit_order(self.id,self.resource,amount,price_per,Side.SELL)
|
order=cx.submit_order(self.id,self.resource,amount,price_per,Side.SELL)
|
||||||
if order==None: # Order failed
|
if order==None: # Order failed
|
||||||
@@ -72,6 +78,7 @@ class Base_Distribution_Agent(BaseAgent,ABC):
|
|||||||
amount=cx.get_account_resource_amount(self.id,"balance")
|
amount=cx.get_account_resource_amount(self.id,"balance")
|
||||||
cx.remove_from_account(self.id,"balance",amount)
|
cx.remove_from_account(self.id,"balance",amount)
|
||||||
self.business.balance+=amount
|
self.business.balance+=amount
|
||||||
|
|
||||||
|
|
||||||
def collect_resource_from_cxs(self,resource):
|
def collect_resource_from_cxs(self,resource):
|
||||||
"""
|
"""
|
||||||
@@ -87,16 +94,37 @@ class Base_Distribution_Agent(BaseAgent,ABC):
|
|||||||
Returns a list of all trades performed by this agent
|
Returns a list of all trades performed by this agent
|
||||||
"""
|
"""
|
||||||
trades=[]
|
trades=[]
|
||||||
|
self.tqty=0
|
||||||
|
self.tincome=0
|
||||||
for cx_id in range(len(self.exchanges)):
|
for cx_id in range(len(self.exchanges)):
|
||||||
cx=self.exchanges[cx_id]
|
cx=self.exchanges[cx_id]
|
||||||
orders=self.orders[cx_id]
|
orders=self.orders[cx_id]
|
||||||
if len(orders)>0:
|
if len(orders)>0:
|
||||||
for k,o in orders.items():
|
for k,o in orders.items():
|
||||||
if k in cx.order_trades_map:
|
if k in cx.order_trades_map:
|
||||||
trades.append(cx.order_trades_map[k])
|
trades.extend(cx.order_trades_map[k])
|
||||||
self.trades=trades
|
self.trades=trades
|
||||||
|
for t in trades:
|
||||||
|
self.tqty+=t.trade_qty
|
||||||
|
self.tincome+=t.trade_qty*t.trade_price
|
||||||
|
self.tincome=round(self.tincome,2)
|
||||||
return trades
|
return trades
|
||||||
|
@property
|
||||||
|
def qty(self):
|
||||||
|
return self.tqty+self.qty_offset
|
||||||
|
@property
|
||||||
|
def income(self):
|
||||||
|
return self.tincome+self.income_offset
|
||||||
|
|
||||||
|
def confirm_distribution(self,dis_qty,step):
|
||||||
|
income_per=self.income/self.qty
|
||||||
|
income_to_confirm=income_per*dis_qty
|
||||||
|
self.income_offset-=income_to_confirm
|
||||||
|
self.qty_offset-=dis_qty
|
||||||
|
self.income_offset=round(self.income_offset,2)
|
||||||
|
|
||||||
|
def reset(self, episode):
|
||||||
|
self.qty_offset=0
|
||||||
|
self.income_offset=0
|
||||||
|
self.trades=[]
|
||||||
|
return super().reset(episode)
|
||||||
@@ -51,7 +51,10 @@ class Price_Believe_Aquire_Agent(Base_Aquire_Agent):
|
|||||||
self.open_orders[cx_id].append({
|
self.open_orders[cx_id].append({
|
||||||
'id': order.order_id,
|
'id': order.order_id,
|
||||||
'lifetime': self.max_price_adj_rate,
|
'lifetime': self.max_price_adj_rate,
|
||||||
|
'leaves': order.leaves_qty
|
||||||
})
|
})
|
||||||
|
if order.leaves_qty!=order.qty:
|
||||||
|
self.update_trades()
|
||||||
|
|
||||||
def tick_open_orders(self) -> int:
|
def tick_open_orders(self) -> int:
|
||||||
"""
|
"""
|
||||||
@@ -65,18 +68,27 @@ class Price_Believe_Aquire_Agent(Base_Aquire_Agent):
|
|||||||
for i in cx_orders:
|
for i in cx_orders:
|
||||||
# Check for each order if it is fullfiled or if it is timed
|
# Check for each order if it is fullfiled or if it is timed
|
||||||
o=self.orders[cx_id][i["id"]]
|
o=self.orders[cx_id][i["id"]]
|
||||||
|
leaves=o.leaves_qty
|
||||||
if o.leaves_qty==0:
|
if o.leaves_qty==0:
|
||||||
#order is done
|
#order is done
|
||||||
self.open_orders[cx_id].remove(i) # remove order from open
|
self.open_orders[cx_id].remove(i) # remove order from open
|
||||||
self.update_believe(cx_id,-1) # update price believe
|
self.update_believe(cx_id,-1) # update price believe
|
||||||
self.collect_balance_from_cxs()
|
self.collect_balance_from_cxs()
|
||||||
self.collect_resource_from_cxs(self.resource)
|
self.collect_resource_from_cxs(self.resource)
|
||||||
|
|
||||||
continue
|
continue
|
||||||
|
if not (i["leaves"]==leaves):
|
||||||
|
#update in order
|
||||||
|
i["leaves"]=leaves
|
||||||
|
self.update_trades()
|
||||||
|
#reset lifetime
|
||||||
|
i["lifetime"]=self.max_price_adj_rate
|
||||||
if i["lifetime"]>0:
|
if i["lifetime"]>0:
|
||||||
self.open_qty+=o.leaves_qty
|
self.open_qty+=o.leaves_qty
|
||||||
i["lifetime"]-=1 # subtract lifetime
|
i["lifetime"]-=1 # subtract lifetime
|
||||||
else:
|
else:
|
||||||
# timeout
|
# timeout
|
||||||
|
self.update_trades()
|
||||||
cx.cancel_order(i["id"])
|
cx.cancel_order(i["id"])
|
||||||
self.collect_balance_from_cxs()
|
self.collect_balance_from_cxs()
|
||||||
self.collect_resource_from_cxs(self.resource)
|
self.collect_resource_from_cxs(self.resource)
|
||||||
|
|||||||
@@ -1,107 +1,123 @@
|
|||||||
from .base_distribution_agent import Base_Distribution_Agent
|
from .base_distribution_agent import Base_Distribution_Agent
|
||||||
import random
|
import random
|
||||||
|
|
||||||
|
|
||||||
class Price_Believe_Distribiute_Agent(Base_Distribution_Agent):
|
class Price_Believe_Distribiute_Agent(Base_Distribution_Agent):
|
||||||
"""
|
"""
|
||||||
Aquire agent with internal price believe system.
|
Aquire agent with internal price believe system.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, simulation, business, resource, exchanges: list, lr, max_price_adj_rate) -> None:
|
def __init__(self, simulation, business, resource, exchanges: list, lr, max_price_adj_rate) -> None:
|
||||||
super().__init__(simulation, business, resource, exchanges)
|
super().__init__(simulation, business, resource, exchanges)
|
||||||
self.lr=lr
|
self.lr = lr
|
||||||
self.max_price_adj_rate=max_price_adj_rate
|
self.max_price_adj_rate = max_price_adj_rate
|
||||||
self.price_believe={i: 1 for i in range(len(self.exchanges))}
|
self.price_believe = {i: 1 for i in range(len(self.exchanges))}
|
||||||
self.open_orders={i: [] for i in range(len(self.exchanges))}
|
self.open_orders = {i: [] for i in range(len(self.exchanges))}
|
||||||
self.open_qty=0
|
self.open_qty = 0
|
||||||
|
|
||||||
|
def tick(self, step, episode):
|
||||||
|
|
||||||
def tick(self,step,episode):
|
order_error = self.target_error()
|
||||||
|
if order_error > 0:
|
||||||
order_error=self.target_error()
|
|
||||||
if order_error>0:
|
|
||||||
# aquire based on current price belive
|
# aquire based on current price belive
|
||||||
cx_id=self.select_best_cx()
|
cx_id = self.select_best_cx()
|
||||||
order=self.distribute_resource(self.price_believe[cx_id],order_error,cx_id)
|
|
||||||
self.register_order(cx_id,order)
|
price=round(self.price_believe[cx_id])
|
||||||
self.tick_open_orders()
|
if price<self.min_price:
|
||||||
|
price=self.min_price
|
||||||
|
order = self.distribute_resource(
|
||||||
|
price, order_error, cx_id)
|
||||||
|
self.register_order(cx_id, order)
|
||||||
|
self.tick_open_orders()
|
||||||
|
|
||||||
def select_best_cx(self):
|
def select_best_cx(self):
|
||||||
best_id=-1
|
best_id = -1
|
||||||
best=-1
|
best = -1
|
||||||
for cx_id in range(len(self.exchanges)):
|
for cx_id in range(len(self.exchanges)):
|
||||||
cx=self.exchanges[cx_id]
|
cx = self.exchanges[cx_id]
|
||||||
available=(cx.get_total_demand(self.resource)>0)
|
available = (cx.get_total_demand(self.resource) > 0)
|
||||||
if available:
|
if available:
|
||||||
potential=1*self.price_believe[cx_id]
|
potential = 1*self.price_believe[cx_id]
|
||||||
else:
|
else:
|
||||||
continue
|
continue
|
||||||
if potential>best:
|
if potential > best:
|
||||||
best=potential
|
best = potential
|
||||||
best_id=cx_id
|
best_id = cx_id
|
||||||
if best_id==-1:
|
if best_id == -1:
|
||||||
best_id=random.randint(0,len(self.exchanges)-1)
|
best_id = random.randint(0, len(self.exchanges)-1)
|
||||||
return best_id
|
return best_id
|
||||||
|
|
||||||
def register_order(self,cx_id,order):
|
def register_order(self, cx_id, order):
|
||||||
self.open_orders[cx_id].append({
|
self.open_orders[cx_id].append({
|
||||||
'id': order.order_id,
|
'id': order.order_id,
|
||||||
'lifetime': self.max_price_adj_rate,
|
'lifetime': self.max_price_adj_rate,
|
||||||
|
'leaves': order.leaves_qty
|
||||||
})
|
})
|
||||||
|
if order.leaves_qty!=order.qty:
|
||||||
|
self.update_trades()
|
||||||
|
|
||||||
def tick_open_orders(self) -> int:
|
def tick_open_orders(self) -> int:
|
||||||
"""
|
"""
|
||||||
Removes 1 from pending orders timeout timer and cancels timeed out orders.
|
Removes 1 from pending orders timeout timer and cancels timeed out orders.
|
||||||
Returns ids of orders that timeed out.
|
Returns ids of orders that timeed out.
|
||||||
"""
|
"""
|
||||||
self.open_qty=0
|
self.open_qty = 0
|
||||||
for cx_id in range(len(self.exchanges)):
|
for cx_id in range(len(self.exchanges)):
|
||||||
cx=self.exchanges[cx_id]
|
cx = self.exchanges[cx_id]
|
||||||
cx_orders=self.open_orders[cx_id]
|
cx_orders = self.open_orders[cx_id]
|
||||||
for i in cx_orders:
|
for i in cx_orders:
|
||||||
# Check for each order if it is fullfiled or if it is timed
|
# Check for each order if it is fullfiled or if it is timed
|
||||||
o=self.orders[cx_id][i["id"]]
|
o = self.orders[cx_id][i["id"]]
|
||||||
if o.leaves_qty==0:
|
leaves=o.leaves_qty
|
||||||
#order is done
|
if o.leaves_qty == 0:
|
||||||
|
# order is done
|
||||||
self.open_orders[cx_id].remove(i) # remove order from open
|
self.open_orders[cx_id].remove(i) # remove order from open
|
||||||
self.update_believe(cx_id,1) # update price believe
|
self.update_believe(cx_id, 1) # update price believe
|
||||||
self.collect_balance_from_cxs()
|
self.collect_balance_from_cxs()
|
||||||
self.collect_resource_from_cxs(self.resource)
|
self.collect_resource_from_cxs(self.resource)
|
||||||
|
self.update_trades()
|
||||||
continue
|
continue
|
||||||
if i["lifetime"]>0:
|
|
||||||
self.open_qty+=o.leaves_qty
|
if not (i["leaves"]==leaves):
|
||||||
i["lifetime"]-=1 # subtract lifetime
|
#update in order
|
||||||
|
i["leaves"]=leaves
|
||||||
|
self.update_trades()
|
||||||
|
#reset lifetime
|
||||||
|
i["lifetime"]=self.max_price_adj_rate
|
||||||
|
|
||||||
|
if i["lifetime"] > 0:
|
||||||
|
self.open_qty += o.leaves_qty
|
||||||
|
i["lifetime"] -= 1 # subtract lifetime
|
||||||
else:
|
else:
|
||||||
# timeout
|
# timeout
|
||||||
|
self.update_trades()
|
||||||
cx.cancel_order(i["id"])
|
cx.cancel_order(i["id"])
|
||||||
self.collect_balance_from_cxs()
|
self.collect_balance_from_cxs()
|
||||||
self.collect_resource_from_cxs(self.resource)
|
self.collect_resource_from_cxs(self.resource)
|
||||||
self.update_believe(cx_id,-1)
|
self.update_believe(cx_id, -1)
|
||||||
self.open_orders[cx_id].remove(i)
|
self.open_orders[cx_id].remove(i)
|
||||||
|
|
||||||
|
|
||||||
|
def update_believe(self, cx_id, modifier):
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def update_believe(self,cx_id,modifier):
|
|
||||||
"""
|
"""
|
||||||
Updates the believe based on the modifier.
|
Updates the believe based on the modifier.
|
||||||
If positive will add lr to believe
|
If positive will add lr to believe
|
||||||
If negative will sub lr to believe
|
If negative will sub lr to believe
|
||||||
"""
|
"""
|
||||||
self.price_believe[cx_id]+=modifier*self.lr
|
self.price_believe[cx_id] += modifier*self.lr
|
||||||
if self.price_believe[cx_id]<0:
|
if self.price_believe[cx_id] < 1:
|
||||||
self.price_believe[cx_id]=0
|
self.price_believe[cx_id] = 1
|
||||||
|
|
||||||
def reset(self,episode):
|
def reset(self, episode):
|
||||||
# Clean shop for today
|
# Clean shop for today
|
||||||
for cx_id in range(len(self.exchanges)):
|
for cx_id in range(len(self.exchanges)):
|
||||||
cx=self.exchanges[cx_id]
|
cx = self.exchanges[cx_id]
|
||||||
cx_orders=self.open_orders[cx_id]
|
cx_orders = self.open_orders[cx_id]
|
||||||
for i in cx_orders:
|
for i in cx_orders:
|
||||||
cx.cancel_order(i["id"])
|
cx.cancel_order(i["id"])
|
||||||
self.collect_balance_from_cxs()
|
self.collect_balance_from_cxs()
|
||||||
self.collect_resource_from_cxs(self.resource)
|
self.collect_resource_from_cxs(self.resource)
|
||||||
# book keeping
|
# book keeping
|
||||||
self.update_trades()
|
self.update_trades()
|
||||||
self.open_orders={i: [] for i in range(len(self.exchanges))}
|
self.open_orders = {i: [] for i in range(len(self.exchanges))}
|
||||||
self.orders={i: {} for i in range(len(self.exchanges))}
|
self.orders = {i: {} for i in range(len(self.exchanges))}
|
||||||
return super().reset(episode)
|
return super().reset(episode)
|
||||||
|
|||||||
@@ -3,35 +3,118 @@ from ..agents.price_believe_aquire import Price_Believe_Aquire_Agent
|
|||||||
from ..agents.price_believe_distribute import Price_Believe_Distribiute_Agent
|
from ..agents.price_believe_distribute import Price_Believe_Distribiute_Agent
|
||||||
from ..agents.autoproduction import AutoProductionAgent
|
from ..agents.autoproduction import AutoProductionAgent
|
||||||
|
|
||||||
class Price_Believe_Business(Business):
|
|
||||||
def __init__(self, id, production, balance,exchange,simulation) -> None:
|
|
||||||
super().__init__(id, production, balance)
|
|
||||||
|
|
||||||
self.distribute=Price_Believe_Distribiute_Agent(simulation,self,production["name"],exchange,0.5,10)
|
|
||||||
self.craft=AutoProductionAgent(simulation,self)
|
|
||||||
self.aquire={}
|
|
||||||
for l in production["prod"]:
|
|
||||||
for k,v in l.items():
|
|
||||||
a=Price_Believe_Aquire_Agent(simulation,self,k,exchange,1,10)
|
|
||||||
a.set_target(v*2)
|
|
||||||
a.set_price_max(10)
|
|
||||||
self.aquire[k]=a
|
|
||||||
self.distribute.set_price_min(10)
|
|
||||||
self.distribute.set_target(0)
|
|
||||||
|
|
||||||
def tick_business_decisions(self,step):
|
class Price_Believe_Business(Business):
|
||||||
for comp in self.production["prod"]:
|
def __init__(self, id, production, balance, exchange, simulation, location) -> None:
|
||||||
for k,v in comp.items():
|
super().__init__(id, production, balance, location)
|
||||||
modifier=1
|
|
||||||
self.aquire[k].set_target(v*modifier)
|
self.expense_per_unit = -1
|
||||||
max_amount=self.production["amount"]*5
|
self.income_per_unit = -1
|
||||||
self.craft.set_target(max_amount)
|
self.distribute = Price_Believe_Distribiute_Agent(
|
||||||
|
simulation, self, production["name"], exchange, 0.2, 10)
|
||||||
|
self.craft = AutoProductionAgent(simulation, self)
|
||||||
|
self.aquire = {}
|
||||||
|
|
||||||
|
for k, v in production["prod"].items():
|
||||||
|
a = Price_Believe_Aquire_Agent(
|
||||||
|
simulation, self, k, exchange, 0.2, 10)
|
||||||
|
a.set_target(v*2)
|
||||||
|
a.set_price_max(10)
|
||||||
|
self.aquire[k] = a
|
||||||
|
self.distribute.set_price_min(10)
|
||||||
|
self.distribute.set_target(0)
|
||||||
|
|
||||||
|
def tick_business_decisions(self, step):
|
||||||
|
if step == 0:
|
||||||
|
|
||||||
|
max_amount = self.production["amount"]*5
|
||||||
|
self.craft.set_target(max_amount)
|
||||||
|
# Update bookkeeping
|
||||||
|
self.update_ex_per_unit()
|
||||||
|
self.update_income_per_unit(step)
|
||||||
|
|
||||||
|
# set target for aquire
|
||||||
|
orderForNewProds = 1
|
||||||
|
prod = self.production["prod"]
|
||||||
|
|
||||||
|
for k, v in prod.items():
|
||||||
|
|
||||||
|
self.aquire[k].set_target(v*orderForNewProds)
|
||||||
|
|
||||||
|
# update production
|
||||||
|
targetUnit = self.production["amount"]*10
|
||||||
|
self.craft.set_target(targetUnit)
|
||||||
|
|
||||||
|
# set min distribute
|
||||||
|
self.distribute.set_price_min(self.expense_per_unit)
|
||||||
|
self.distribute.set_target(0)
|
||||||
|
|
||||||
|
def tick_business_episode(self, episode_count):
|
||||||
|
start_balance = self.balance_history[-1]
|
||||||
|
diff = self.balance-start_balance
|
||||||
|
if diff > 0:
|
||||||
|
# we have some profit -> increase production staff
|
||||||
|
self.craft.set_worker(self.craft.worker+1)
|
||||||
|
else:
|
||||||
|
self.craft.set_worker(self.craft.worker-1)
|
||||||
|
|
||||||
def resource_in_possesion(self):
|
def resource_in_possesion(self):
|
||||||
return self.distribute.open_qty+self.inventory[self.production["name"]]
|
return self.distribute.open_qty+self.inventory[self.production["name"]]
|
||||||
|
|
||||||
|
def update_ex_per_unit(self):
|
||||||
|
experunit = 0
|
||||||
|
prod = self.production["prod"]
|
||||||
|
amount = self.production["amount"]
|
||||||
|
qtyNewProds = -1
|
||||||
|
for key, agent in self.aquire.items():
|
||||||
|
agent.update_trades()
|
||||||
|
if agent.qty == 0:
|
||||||
|
return
|
||||||
|
if agent.qty<0:
|
||||||
|
print("pla")
|
||||||
|
req = prod[key]
|
||||||
|
|
||||||
|
covers = agent.qty/req
|
||||||
|
|
||||||
|
if qtyNewProds == -1:
|
||||||
|
qtyNewProds = covers
|
||||||
|
if qtyNewProds > covers:
|
||||||
|
qtyNewProds = covers
|
||||||
|
|
||||||
|
ExPerProd = agent.expense/covers
|
||||||
|
experunit += ExPerProd/amount
|
||||||
|
|
||||||
|
if qtyNewProds > 0:
|
||||||
|
# confirm new units
|
||||||
|
for key, agent in self.aquire.items():
|
||||||
|
qtyToConfirm = prod[key]*qtyNewProds
|
||||||
|
agent.confirm_purchase(qtyToConfirm)
|
||||||
|
a=1+2
|
||||||
|
|
||||||
|
qtyNewUnits = qtyNewProds*amount
|
||||||
|
|
||||||
|
# if we havent set the expense_per_unit
|
||||||
|
if self.expense_per_unit == -1:
|
||||||
|
self.expense_per_unit = experunit
|
||||||
|
return
|
||||||
|
# update expense per unit
|
||||||
|
prev_ex_total = self.expense_per_unit*self.resource_in_possesion()
|
||||||
|
new_ex_total = qtyNewUnits*experunit
|
||||||
|
ex_total = prev_ex_total+new_ex_total
|
||||||
|
estimatedQTYUnits = qtyNewUnits+self.resource_in_possesion()
|
||||||
|
new_ex = ex_total/estimatedQTYUnits
|
||||||
|
self.expense_per_unit = new_ex
|
||||||
|
|
||||||
|
def update_income_per_unit(self,step):
|
||||||
|
qty_sold = self.distribute.qty
|
||||||
|
income = self.distribute.income
|
||||||
|
if income==0:
|
||||||
|
return
|
||||||
|
self.income_per_unit = qty_sold/income
|
||||||
|
self.distribute.confirm_distribution(qty_sold,step)
|
||||||
|
|
||||||
def close_business(self):
|
def close_business(self):
|
||||||
for k,a in self.aquire.items():
|
for k, a in self.aquire.items():
|
||||||
a.unregister()
|
a.unregister()
|
||||||
self.distribute.unregister()
|
self.distribute.unregister()
|
||||||
self.craft.unregister()
|
self.craft.unregister()
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
@@ -1,7 +1,7 @@
|
|||||||
from abc import ABC
|
from abc import ABC
|
||||||
import log
|
import log
|
||||||
class Business(ABC):
|
class Business(ABC):
|
||||||
def __init__(self,id,production,balance) -> None:
|
def __init__(self,id,production,balance,location) -> None:
|
||||||
"""production (dict): {
|
"""production (dict): {
|
||||||
name: 'Gem',
|
name: 'Gem',
|
||||||
amount: 4,
|
amount: 4,
|
||||||
@@ -13,14 +13,17 @@ class Business(ABC):
|
|||||||
balance (int): Starting Balance
|
balance (int): Starting Balance
|
||||||
"""
|
"""
|
||||||
self.id=id
|
self.id=id
|
||||||
|
self.location=location
|
||||||
self.production=production
|
self.production=production
|
||||||
self.balance_history=[balance]
|
self.balance_history=[balance]
|
||||||
self.balance=balance
|
self.balance=balance
|
||||||
|
self.expense=0
|
||||||
|
self.income=0
|
||||||
#Setup Inventory
|
#Setup Inventory
|
||||||
self.inventory={production["name"]: 0}
|
self.inventory={production["name"]: 0}
|
||||||
for l in production["prod"]:
|
|
||||||
for k,v in l.items():
|
for k,v in production["prod"].items():
|
||||||
self.inventory[k]=0
|
self.inventory[k]=0
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def tick(self,step):
|
def tick(self,step):
|
||||||
@@ -34,8 +37,10 @@ class Business(ABC):
|
|||||||
"""
|
"""
|
||||||
Call for resetting for the next episode
|
Call for resetting for the next episode
|
||||||
"""
|
"""
|
||||||
self.balance_history.append(self.balance)
|
|
||||||
self.tick_business_episode(episode_count)
|
self.tick_business_episode(episode_count)
|
||||||
|
self.balance_history.append(self.balance)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def tick_business_episode(self,episode_count):
|
def tick_business_episode(self,episode_count):
|
||||||
@@ -54,5 +59,8 @@ class Business(ABC):
|
|||||||
data["step"]=step
|
data["step"]=step
|
||||||
data["tstep"]=step+episode*episode_length
|
data["tstep"]=step+episode*episode_length
|
||||||
data["production"]=self.production["name"]
|
data["production"]=self.production["name"]
|
||||||
|
data["prod_inventory"]=self.inventory[self.production["name"]]
|
||||||
|
data["raw_inventory"]=self.inventory[self.production["name"]]
|
||||||
data["balance"]=self.balance
|
data["balance"]=self.balance
|
||||||
|
data["location"]=self.location
|
||||||
log.BUSINESSData.append(data)
|
log.BUSINESSData.append(data)
|
||||||
Binary file not shown.
@@ -40,10 +40,10 @@ def search_yaml_files(directory = "db"):
|
|||||||
productions[comm['name']]=[]
|
productions[comm['name']]=[]
|
||||||
productions[comm['name']].append(comm)
|
productions[comm['name']].append(comm)
|
||||||
productions_id_map[comm["id"]]=comm
|
productions_id_map[comm["id"]]=comm
|
||||||
for comp in comm["prod"]:
|
k=comm["prod"].keys()
|
||||||
k=list(comp.keys())[0]
|
for component in k:
|
||||||
if k not in productions_uses:
|
if component not in productions_uses:
|
||||||
productions_uses[k]=[]
|
productions_uses[component]=[]
|
||||||
productions_uses[k].append(comm)
|
productions_uses[component].append(comm)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -126,7 +126,7 @@ class Exchange():
|
|||||||
"""
|
"""
|
||||||
# calculate price for complete order fullfilment
|
# calculate price for complete order fullfilment
|
||||||
amount=int(amount)
|
amount=int(amount)
|
||||||
full_price=price*amount
|
full_price=round(price*amount,2)
|
||||||
|
|
||||||
|
|
||||||
# Move resources into escrow
|
# Move resources into escrow
|
||||||
|
|||||||
+16
-14
@@ -34,6 +34,7 @@ class Simulation():
|
|||||||
def set_cells(self,cells):
|
def set_cells(self,cells):
|
||||||
for c in cells:
|
for c in cells:
|
||||||
self.cells[c.name]=c
|
self.cells[c.name]=c
|
||||||
|
self.populated_cells[c.name]=0
|
||||||
|
|
||||||
def set_businesses(self,bus):
|
def set_businesses(self,bus):
|
||||||
self.businesses=bus
|
self.businesses=bus
|
||||||
@@ -93,7 +94,7 @@ class Simulation():
|
|||||||
self.timings["dss"]+=setup-start
|
self.timings["dss"]+=setup-start
|
||||||
self.timings["dsa"]+=agentstep-setup
|
self.timings["dsa"]+=agentstep-setup
|
||||||
self.timings["dsap"]=self.timings["dsa"]/(len(self.tick_funcs)+1)
|
self.timings["dsap"]=self.timings["dsa"]/(len(self.tick_funcs)+1)
|
||||||
self.timings["dab"]+=busstep-agentstep
|
self.timings["dab"]+=(busstep-agentstep)/(len(self.businesses)+1)
|
||||||
self.timings["dbl"]+=logstep-busstep
|
self.timings["dbl"]+=logstep-busstep
|
||||||
self.timings["dt"]+=logstep-start
|
self.timings["dt"]+=logstep-start
|
||||||
|
|
||||||
@@ -157,10 +158,10 @@ class Simulation():
|
|||||||
cell_id=random.choice(cells)
|
cell_id=random.choice(cells)
|
||||||
cell=self.cells[cell_id]
|
cell=self.cells[cell_id]
|
||||||
cxs=[cell.exchange,self.cx]
|
cxs=[cell.exchange,self.cx]
|
||||||
self.populated_cells[cell_id]=True
|
business=Price_Believe_Business.Price_Believe_Business(uuid.UUID(int=random.getrandbits(128)),prod,1000,cxs,self,cell_id)
|
||||||
business=Price_Believe_Business.Price_Believe_Business(uuid.uuid4(),prod,1000,cxs,self)
|
|
||||||
self.businesses.append(business)
|
self.businesses.append(business)
|
||||||
self.production_util[selected_prod]+=1
|
self.production_util[selected_prod]+=1
|
||||||
|
self.populated_cells[cell_id]+=1
|
||||||
return business
|
return business
|
||||||
|
|
||||||
def remove_business(self,id):
|
def remove_business(self,id):
|
||||||
@@ -173,6 +174,7 @@ class Simulation():
|
|||||||
bus.close_business()
|
bus.close_business()
|
||||||
self.businesses.remove(bus)
|
self.businesses.remove(bus)
|
||||||
self.production_util[bus.production["id"]]-=1
|
self.production_util[bus.production["id"]]-=1
|
||||||
|
self.populated_cells[bus.location]-=1
|
||||||
|
|
||||||
|
|
||||||
def get_max_profit_prod(self):
|
def get_max_profit_prod(self):
|
||||||
@@ -183,7 +185,7 @@ class Simulation():
|
|||||||
|
|
||||||
for b in self.businesses:
|
for b in self.businesses:
|
||||||
id=b.production["id"]
|
id=b.production["id"]
|
||||||
diff=b.balance-b.balance_history[-1]
|
diff=b.balance-b.balance_history[-2]
|
||||||
if id not in profit:
|
if id not in profit:
|
||||||
profit[id]=0
|
profit[id]=0
|
||||||
profit[id]+=diff
|
profit[id]+=diff
|
||||||
@@ -208,16 +210,15 @@ class Simulation():
|
|||||||
cx=cell.exchange
|
cx=cell.exchange
|
||||||
# Best prod resource availability
|
# Best prod resource availability
|
||||||
# Using the exchange in that cell, lookup supply or demand of resources. Supply +1 / Demand -1
|
# Using the exchange in that cell, lookup supply or demand of resources. Supply +1 / Demand -1
|
||||||
for prod_item in prod["prod"]:
|
for key,val in prod["prod"].items():
|
||||||
key=list(prod_item.keys())[0]
|
|
||||||
val=prod_item[key]
|
|
||||||
a=cx.get_total_supply(key)
|
a=cx.get_total_supply(key)
|
||||||
cell_score[cell.name]+=(cx.get_total_supply(key)/val)
|
cell_score[cell.name]+=(cx.get_total_supply(key)/val)
|
||||||
cell_score[cell.name]-=(cx.get_total_demand(key)/val)
|
cell_score[cell.name]-=(cx.get_total_demand(key)/val)
|
||||||
# If demand for prod item in cell then score +1/ score -1 if supply is already there
|
# If demand for prod item in cell then score +1/ score -1 if supply is already there
|
||||||
a=cx.get_total_demand(prod["name"])
|
a=cx.get_total_demand(prod["name"])
|
||||||
cell_score[cell.name]+=cx.get_total_demand(prod["name"])
|
b=cx.get_total_supply(prod["name"])
|
||||||
cell_score[cell.name]-=cx.get_total_supply(prod["name"])
|
cell_score[cell.name]+=a
|
||||||
|
cell_score[cell.name]-=b
|
||||||
max_keys = [key for key, value in cell_score.items() if value == max(cell_score.values())]
|
max_keys = [key for key, value in cell_score.items() if value == max(cell_score.values())]
|
||||||
return max_keys
|
return max_keys
|
||||||
|
|
||||||
@@ -246,11 +247,12 @@ class Simulation():
|
|||||||
return cx.log_step(name,epi,epilen,tick,False)
|
return cx.log_step(name,epi,epilen,tick,False)
|
||||||
|
|
||||||
def log_cxs_episode(self):
|
def log_cxs_episode(self):
|
||||||
for id,_ in self.populated_cells.items():
|
for id,v in self.populated_cells.items():
|
||||||
cell=self.cells[id]
|
if v>0:
|
||||||
lcx=cell.exchange
|
cell=self.cells[id]
|
||||||
name="lcx_{}".format(id)
|
lcx=cell.exchange
|
||||||
lcx.log_episode(name,self.episode_count)
|
name="lcx_{}".format(id)
|
||||||
|
lcx.log_episode(name,self.episode_count)
|
||||||
self.cx.log_episode("cx",self.episode_count)
|
self.cx.log_episode("cx",self.episode_count)
|
||||||
|
|
||||||
def log_business_tick(self,episode_length):
|
def log_business_tick(self,episode_length):
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ from econ.commoditys import commoditys
|
|||||||
from econ.cells import db, cell
|
from econ.cells import db, cell
|
||||||
import log
|
import log
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
|
import uuid
|
||||||
db.load_world("db/world.json")
|
db.load_world("db/world.json")
|
||||||
|
|
||||||
commoditys.search_yaml_files()
|
commoditys.search_yaml_files()
|
||||||
@@ -28,21 +29,24 @@ cxs=[cx]
|
|||||||
#cx.submit_order(w,"Wood",0,1000,Side.BUY)
|
#cx.submit_order(w,"Wood",0,1000,Side.BUY)
|
||||||
#cx.submit_order(2,"Gem",1,10,Side.SELL)
|
#cx.submit_order(2,"Gem",1,10,Side.SELL)
|
||||||
|
|
||||||
|
|
||||||
sim=Simulation()
|
sim=Simulation()
|
||||||
sim.seed(42)
|
sim.seed(42)
|
||||||
sim.set_cells(cells)
|
sim.set_cells(cells)
|
||||||
sim.reset()
|
sim.reset()
|
||||||
#sim.tick(1)
|
for i in range(100):
|
||||||
|
sim.tick(100)
|
||||||
|
sim.reset()
|
||||||
# create info
|
# create info
|
||||||
while len(sim.get_underutelized_prods(5))>0:
|
while len(sim.get_underutelized_prods(1))>0:
|
||||||
sim.create_bussiness(5)
|
sim.create_bussiness(1)
|
||||||
#sim.reset()
|
#sim.reset()
|
||||||
for a in tqdm(range(50)):
|
for a in tqdm(range(200)):
|
||||||
for i in range(100):
|
for i in range(100):
|
||||||
sim.tick(100)
|
sim.tick(100)
|
||||||
print(f"|Stats| Num of Businesses: {len(sim.businesses)} Num Tickfunk: {len(sim.tick_funcs)} Time Agent Tick: {sim.timings['dsa']} Time Logging {sim.timings['dbl']}")
|
print(f"|Stats| Num of Businesses: {len(sim.businesses)} Num Tickfunk: {len(sim.tick_funcs)} Time Agent Tick: {sim.timings['dsa']} Time Logging {sim.timings['dbl']}")
|
||||||
sim.reset()
|
sim.reset()
|
||||||
sim.create_bussiness(3)
|
sim.create_bussiness(1)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user