Skip to content

Commit

Permalink
main-fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
rangoiv committed Apr 10, 2024
1 parent 668638e commit c67b212
Show file tree
Hide file tree
Showing 13 changed files with 157 additions and 129 deletions.
8 changes: 4 additions & 4 deletions backend/fixtures/orderbook_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,24 +109,24 @@ def check_trade(trade: Trade):
sell_order = trade.sell_order

if buy_order is None or sell_order is None:
assert trade.total_money == 0
assert trade.total_price == 0
assert trade.trade_size == 0
assert trade.trade_price is None
return {"can_buy": False, "can_sell": False}

buyer_id = buy_order.player_id
seller_id = sell_order.player_id

can_buy = traders[buyer_id].money >= trade.total_money
can_buy = traders[buyer_id].money >= trade.total_price
can_sell = traders[seller_id].resources.coal >= trade.trade_size

if not can_buy or not can_sell:
return {"can_buy": can_buy, "can_sell": can_sell}

traders[buyer_id].money -= trade.total_money
traders[buyer_id].money -= trade.total_price
traders[buyer_id].resources.coal += trade.trade_size

traders[seller_id].money += trade.total_money
traders[seller_id].money += trade.total_price
traders[seller_id].resources.coal -= trade.trade_size

return {"can_buy": True, "can_sell": True}
Expand Down
2 changes: 1 addition & 1 deletion backend/game/market/energy_market.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def create_trade(self, player: Player, tick, energy: int, energy_price: int):
self.trades.append(Trade(
trade_price=energy_price,
trade_size=energy,
total_money=energy * energy_price,
total_price=energy * energy_price,
tick=tick,
buy_order_id="energy market",
sell_order_id="energy market",
Expand Down
6 changes: 3 additions & 3 deletions backend/game/market/resource_market.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def _check_trade(self, trade: Trade):
elif buyer.is_bot:
can_buy = True
else:
can_buy = buyer.money >= trade.total_money
can_buy = buyer.money >= trade.total_price

if seller is None:
can_sell = False
Expand All @@ -97,11 +97,11 @@ def _on_trade(self, trade: Trade):
logger.critical(f"Trading between two different bots {buyer.player_name} {buyer_id}({buyer.game_id}) and {seller.player_name} {seller_id}({seller.game_id}) in game ({self.game_id}). This is probably due to invalid reseting of the game.")

if not buyer.is_bot:
buyer.money -= trade.total_money
buyer.money -= trade.total_price
buyer.resources[self.resource] += trade.trade_size

if not seller.is_bot:
seller.money += trade.total_money
seller.money += trade.total_price
seller.resources[self.resource] -= trade.trade_size

def _get_player(self, player_id: str) -> Player:
Expand Down
8 changes: 4 additions & 4 deletions backend/game/orderbook/orderbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,11 @@ def _match_condition(self):
def _match_one(self, buy_order: Order, sell_order: Order, tick: int):
trade_price = self._get_trade_price(buy_order, sell_order)
trade_size = self._get_trade_size(buy_order, sell_order)
total_money = trade_price * trade_size
total_price = trade_price * trade_size

trade = Trade(
tick=tick,
total_money=total_money,
total_price=total_price,
trade_size=trade_size,
trade_price=trade_price)
trade.buy_order = buy_order
Expand All @@ -178,8 +178,8 @@ def _match_one(self, buy_order: Order, sell_order: Order, tick: int):
buy_order.filled_size += trade_size
sell_order.filled_size += trade_size

buy_order.filled_money += total_money
sell_order.filled_money += total_money
buy_order.filled_money += total_price
sell_order.filled_money += total_price

buy_order.filled_price = buy_order.filled_money / buy_order.filled_size
sell_order.filled_price = sell_order.filled_money / sell_order.filled_size
Expand Down
4 changes: 2 additions & 2 deletions backend/game/orderbook/test_orderbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def check_trade(*args, **kwargs):
assert trade.sell_order is sell_order
assert trade.buy_order.order_status == OrderStatus.COMPLETED
assert trade.sell_order.order_status == OrderStatus.COMPLETED
assert trade.total_money == price * size
assert trade.total_price == price * size
assert trade.trade_price == price
assert trade.trade_size == size
assert trade.tick == 1
Expand Down Expand Up @@ -253,7 +253,7 @@ def test_prev_price(get_order):
orderbook.match(tick=1)

assert len(trades) == 1
assert trades[0].total_money == 5 * 50
assert trades[0].total_price == 5 * 50


def test_invalid_callback_type():
Expand Down
2 changes: 1 addition & 1 deletion backend/game/price_tracker/price_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def _calculate_low_high(self, trades: List[Trade]):

for trade in trades:
price = trade.trade_price
money_sum += trade.total_money
money_sum += trade.total_price
money_size += trade.trade_size

if self.high is None:
Expand Down
10 changes: 7 additions & 3 deletions backend/game/tick/ticker.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,9 +225,13 @@ def get_score_name(player: Player):
scores=scores)

def get_players_and_enter_context(self, game: Game, stack: ExitStack) -> Dict[str, Player]:
players = Player.find(Player.game_id == game.game_id).all()
for player_lock in list(map(methodcaller('lock'), players)):
stack.enter_context(player_lock)
players: List[Player] = Player.find(Player.game_id == game.game_id).all()
for player in players:
try:
stack.enter_context(player.lock())
except Exception:
logger.critical(f"Error getting lock for player {player.player_name} {player.player_id} in game {player.game_id}")

player_pks = map(attrgetter('pk'), players)
players = list(map(Player.get, player_pks))
players = {player.player_id: player for player in players}
Expand Down
8 changes: 2 additions & 6 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,6 @@
from docs import tags_metadata, short_description
from redis_om import Migrator
from fastapi.middleware.cors import CORSMiddleware
import sys


if "pytest" not in sys.modules:
Migrator().run()


tick_event = asyncio.Event()
Expand All @@ -44,6 +39,7 @@ async def run_game_ticks():

@asynccontextmanager
async def lifespan(app: FastAPI):
Migrator().run()
asyncio.create_task(run_game_ticks())
yield

Expand All @@ -62,7 +58,7 @@ async def lifespan(app: FastAPI):

app.add_middleware(
CORSMiddleware,
allow_origins="*",
allow_origins="Access-Control-Allow-Origin",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
Expand Down
2 changes: 1 addition & 1 deletion backend/model/trade.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
class Trade(JsonModel):
tick: int = Field(index=True)

total_money: int
total_price: int
trade_size: int
trade_price: int

Expand Down
Loading

0 comments on commit c67b212

Please sign in to comment.