Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enum types, config, orders endpoint, bug fixes #76

Merged
merged 7 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions backend/config.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import yaml
import os
import re

path_matcher = re.compile(r'\$\{([^}^{]+)\}')
def path_constructor(loader, node):
value = node.value
match = path_matcher.match(value)
env_var = match.group()[2:-1]
val = os.environ.get(env_var, None)
if value[match.end():]:
return val + value[match.end():]
return val

with open("config.yaml", "r") as file:
config = yaml.load(file, Loader=yaml.SafeLoader)
yaml.add_implicit_resolver('!path', path_matcher)
yaml.add_constructor('!path', path_constructor)

config['testing'] = os.environ.get('TESTING', False)
with open("config.yaml", "r") as file:
config = yaml.load(file, Loader=yaml.FullLoader)
28 changes: 16 additions & 12 deletions backend/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@ server:
port: 8000
host: 0.0.0.0

redis:
port: 6379

database:
url: postgresql://postgres:postgres@localhost:5432/mydatabase

test_database:
url: postgresql://postgres:postgres@localhost:5432/test_database

admin:
secret: mojkljuc

testing: ${TESTING}
debug: ${DEBUG}

dataset:
datasets_path: ./data
max_ticks_in_request: 100
Expand All @@ -27,20 +42,9 @@ dataset:

energy_demand_multiplier: 55100

redis:
port: 6379

database:
url: postgresql://postgres:postgres@localhost:5432/mydatabase

test_database:
url: postgresql://postgres:postgres@localhost:5432/test_database

admin:
secret: mojkljuc

player:
starting_money: 350000
max_orders: 10

bots:
team_name: bots
Expand Down
4,862 changes: 2,431 additions & 2,431 deletions backend/data/df_2431_2011-11-06 03:30:00_2012-02-15 09:30:00.csv

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions backend/db/migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ async def fill_tables():
tick_time=1000)

for game_id in [not_nat_game_id, nat_game_id]:
await Player.create(player_name="Goran", is_active=True, is_bot=False, game_id=game_id, team_id=g_team_id, money=15000, coal=1000)
await Player.create(player_name="Kruno", is_active=True, is_bot=False, game_id=game_id, team_id=k_team_id)
await Player.create(player_name="Zvone", is_active=True, is_bot=False, game_id=game_id, team_id=z_team_id)
await Player.create(player_name="Goran", is_active=True, is_bot=False, game_id=game_id, team_id=g_team_id, money=350000, coal=1000)
await Player.create(player_name="Kruno", is_active=True, is_bot=False, game_id=game_id, team_id=k_team_id, money=350000, coal=1000)
await Player.create(player_name="Zvone", is_active=True, is_bot=False, game_id=game_id, team_id=z_team_id, money=350000, coal=1000)

logger.info("Filled database with dummy data")

Expand Down
5 changes: 1 addition & 4 deletions backend/game/bots/resource_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,6 @@ async def run(self, tick_data: TickData):
orders = await self.get_last_orders()

for resource in Resource:
if resource == Resource.energy:
continue

resource_orders = orders[resource]
resource_sum = resources_sum[resource]
buy_price = self.buy_prices[resource]
Expand Down Expand Up @@ -93,7 +90,7 @@ async def run(self, tick_data: TickData):
self.buy_prices[resource] = buy_price
self.sell_prices[resource] = sell_price

def mix_dataset_price(self, dataset_row, price, resource):
def mix_dataset_price(self, dataset_row, price, resource: Resource):
return dataset_price_weight * dataset_row[resource.name.lower() + "_price"] + (1 - dataset_price_weight) * price

def get_filled_perc(self, orders: List[Order]):
Expand Down
104 changes: 41 additions & 63 deletions backend/game/fixtures/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,40 @@
import pandas as pd
from game.tick import TickData, Ticker
from game.tick.ticker import GameData
from model import Order, Player, Resource, Game, PowerPlantType, OrderSide
from model import Order, Player, Resource, Game, OrderSide
from game.market import ResourceMarket, EnergyMarket
import pytest
from model.dataset_data import DatasetData

from model.order_types import OrderStatus

@pytest.fixture
def team_id():
return 1


@pytest.fixture
def game_id():
return 1


@pytest.fixture
def game():
return Game(game_id=1,
game_name=f"game_{game_id}",
is_contest=False,
bots="",
dataset_id=1,
start_time=pd.Timestamp.now(),
total_ticks=1000,
tick_time=1000,
)


@pytest.fixture
def game_data(game):
return GameData(game)


@pytest.fixture
def dataset_row():
return DatasetData(
Expand All @@ -38,58 +59,21 @@ def dataset_row():


@pytest.fixture
def game():
return Game(game_id=1,
game_name=f"game_{game_id}",
is_contest=False,
bots="",
dataset_id=1,
start_time=pd.Timestamp.now(),
total_ticks=1000,
tick_time=1000,
)


@pytest.fixture
def team_id():
return 1


@pytest.fixture
def get_game_data(game):
game_id = 1

def get_game_data(**kwargs) -> Game:
nonlocal game_id
game_data = GameData(game, **kwargs)
return game_data

return get_game_data
def ticker(game_data):
ticker = Ticker()
ticker.game_data = {1: game_data}
return ticker


@pytest.fixture
def get_ticker(game, get_game_data):
def get_ticker(players) -> Ticker:
ticker = Ticker()
ticker.game_data = {1: get_game_data(players=players)}
return ticker
return get_ticker


@pytest.fixture
def get_tick_data(game_id):
def get_tick_data(markets, players, user_cancelled_orders=[], pending_orders=[], updated_orders=[], coal=100, energy_demand=100, max_energy_price=100) -> TickData:
def get_tick_data(game, energy_market):
def get_tick_data(markets, players,
user_cancelled_orders=[],
pending_orders=[], updated_orders=[],
coal=100, energy_demand=100,
max_energy_price=100) -> TickData:
tick_data = TickData(
game=Game(
game_id=game_id,
game_name=f"game_{game_id}",
is_contest=False,
bots="",
dataset_id=1,
start_time=pd.Timestamp.now(),
total_ticks=1000,
tick_time=1000,
),
game=game,
bots=[],
dataset_row=DatasetData(
dataset_data_id=1,
Expand Down Expand Up @@ -117,7 +101,8 @@ def get_tick_data(markets, players, user_cancelled_orders=[], pending_orders=[],
players=players,
user_cancelled_orders=user_cancelled_orders,
pending_orders=pending_orders,
updated_orders=updated_orders
updated_orders=updated_orders,
energy_market=energy_market
)

return tick_data
Expand Down Expand Up @@ -165,14 +150,16 @@ def get_player_in_game(**kwargs) -> Player:
def get_order():
order_id = 0

def get_order(player_id: int, price: int, size: int, order_side: OrderSide, tick: int) -> Order:
def get_order(player_id: int, price: int,
size: int, order_side: OrderSide,
tick: int) -> Order:
nonlocal order_id
order = Order(
order_id=order_id,
game_id=1,
timestamp=pd.Timestamp.now(),
player_id=player_id,
resource=Resource.coal.value,
resource=Resource.coal,
price=price,
tick=tick,
size=size,
Expand All @@ -189,18 +176,9 @@ def get_player_dict(players: List[Player]) -> Dict[int, Player]:

@pytest.fixture
def coal_market():
def get_coal_market(players: Dict[int, Player] = {}) -> ResourceMarket:
return ResourceMarket(Resource.coal, players)
return get_coal_market
return ResourceMarket(Resource.coal)


@pytest.fixture
def energy_market():
return EnergyMarket()


@pytest.fixture
def get_energy_market():
def get_energy_market() -> EnergyMarket:
return EnergyMarket()
return get_energy_market
5 changes: 3 additions & 2 deletions backend/game/fixtures/orderbook_fixtures.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pytest
import pandas as pd
import random
from model import Order, OrderSide, Trade
from model import Order, OrderSide, Trade, Resource


@pytest.fixture(autouse=True)
Expand Down Expand Up @@ -60,7 +60,8 @@ def get_order(player_id: int, price: int, size: int, order_side: OrderSide, time
price=price,
size=size,
order_side=order_side,
tick=tick)
tick=tick,
resource=Resource.coal)
return get_order


Expand Down
23 changes: 20 additions & 3 deletions backend/game/market/energy_market.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
from typing import Dict
from model import Trade, Resource
from model.order import Order
import pandas as pd
from game.price_tracker.price_tracker import PriceTracker
from model import Trade
from config import config
from model.player import Player


class EnergyMarket:

def __init__(self):
self.price_tracker = PriceTracker()

def match(self, players: Dict[int, Player], demand: int, max_price: int) -> Dict[int, int]:
players_sorted = sorted(players.values(), key=lambda x: x.energy_price)
players_sorted = [
Expand All @@ -14,21 +19,33 @@ def match(self, players: Dict[int, Player], demand: int, max_price: int) -> Dict
max_per_player = int(demand * config["max_energy_per_player"])

orders = {}
trades = []

for player in players_sorted:
to_sell = min(player.energy, demand, max_per_player)

if to_sell == 0:
if to_sell <= 0:
continue

# player.energy -= to_sell # ne trebamo, zelimo da im se prikaze koliko proizvode
demand -= to_sell

player.money += to_sell * player.energy_price

trades.append(Trade(
buy_order=None,
sell_order=None,
filled_price=player.energy_price,
filled_size=to_sell,
filled_money=to_sell * player.energy_price,
timestamp=pd.Timestamp.now(),
))

orders[player.player_id] = to_sell

if demand == 0:
break

self.price_tracker.on_end_match(trades)

return orders
Loading
Loading