市场系统设计

Market System Design

Overview

The market system simulates a dynamic marketplace where prices adjust based on supply and demand. All traders (AI and player) buy and sell commodities through the Market Entity (Trader ID: 22), and their trading activity directly influences commodity prices.


Key Components

1. Market Entity

  • ID: Trader ID 22
  • Type: Special trader entity with high liquidity
  • Role: Acts as the counterparty for all trades
  • Holdings: Maintains large reserves of all commodities

2. MarketManager

Located at: gdt/scripts/core/managers/market_manager.gd

Responsibilities:

  • Track buy/sell volumes for each commodity
  • Calculate net demand (buy pressure - sell pressure)
  • Adjust prices based on demand
  • Generate price series for chart display
  • Manage market parameters

Key Methods:

  • record_market_trade(commodity_id, quantity, is_buy) - Records a trade with the market
  • get_market_demand(commodity_id) - Returns current demand data for a commodity
  • set_market_parameters(params) - Adjusts market behavior parameters

3. TradeManager

Located at: gdt/scripts/trade/trade_manager.gd

Integration:

  • Detects trades involving Market Entity (ID 22)
  • Automatically reports trades to MarketManager
  • Continues to handle all transfer logic

How It Works

Trade Flow

  1. Trader initiates buy/sell with Market Entity
  2. TradeManager executes the transfer
  3. TradeManager checks if Market Entity is involved
  4. If yes, calls MarketManager.record_market_trade()
  5. MarketManager updates demand tracking
  6. On next price tick, demand influences price calculation

Price Calculation

Each price point is calculated as:

price_change = random_volatility + trend_change + demand_impact

demand_impact = net_demand × price_sensitivity × current_price
demand_impact = clamp(demand_impact, -max_change, +max_change)

new_price = current_price + price_change

Where:

  • net_demand: buy_volume - sell_volume (smoothed)
  • price_sensitivity: How much demand affects price (default: 0.0015)
  • max_change: Maximum price change per tick (default: 5%)

Demand Decay

Demand naturally decays over time to prevent permanent price trends:

D(t) = D(0) × (0.95)^t

半衰期 ≈ 14 tick

Market Parameters

Can be adjusted via MarketManager.set_market_parameters():

Parameter Default Range Description
demand_decay_rate 0.95 0.1-1.0 How fast demand fades (higher = slower decay)
price_sensitivity 0.0015 0.0001+ How much demand affects price
max_price_change_per_tick 0.05 0.01-0.5 Maximum single tick price change (%)
demand_smoothing 0.3 0.0-1.0 How quickly demand responds (lower = smoother)

Example Usage

Recording a Trade

# Automatic - happens in TradeManager when trading with Market Entity
trade_manager.execute_transfer(
    commodity_id,
    player_id, "trader",    # From player
    22, "trader",           # To market entity
    quantity,
    "personal_bag"
)
# ↓ Automatically calls ↓
# market_manager.record_market_trade(commodity_id, quantity, false)

Checking Market Demand

var demand = market_manager.get_market_demand(commodity_id)
print("Buy Volume: ", demand.buy_volume)
print("Sell Volume: ", demand.sell_volume)
print("Net Demand: ", demand.net_demand)

Adjusting Market Behavior

# Make market more sensitive to trades
market_manager.set_market_parameters({
    "price_sensitivity": 0.003,  # Double sensitivity
    "demand_decay_rate": 0.90,   # Faster decay
})

Debugging

# Print full market status
market_manager.debug_print_market_demand()

# Output:
# === 市场需求状态 ===
# 追踪的商品数量: 3
#
# 商品: 铁矿石 (ID: 3)
#   当前价格: $15.23
#   买入量: 45.20
#   卖出量: 12.30
#   净需求: 32.90 (买方压力)
#   价格影响: +0.75 (4.92%)

UI Integration

The trading chart (trading_chart.gd) automatically displays market prices:

  • Reads current_value from commodities via MarketManager
  • Displays price series generated by MarketManager
  • No changes needed - prices update automatically

Memory-Only Design

All market data is kept in memory:

  • No SQL writes for price updates
  • Fast performance
  • SQL database only used for initialization
  • Data resets on game restart (by design)

Future Enhancements

Potential improvements:

  1. Order book simulation (bid/ask spreads)
  2. Market maker algorithms for better liquidity
  3. Price circuit breakers for extreme volatility
  4. Historical data persistence
  5. Multiple market entities (regional markets)
  6. Commodity-specific parameters