StockMarket wAPI

A virtual stock market mod for Minecraft 1.21.1 (NeoForge) with AI-driven news and real-time price changes based on player demand. Uses a custom currency (KABU) and relies on aidbwapi_core for AI and data storage.

by
45 Downloads
neoforgeeconomygame-mechanicssocial
Rent Server with this Mod

About this Mod

  1. English / 2. 日本語

StockMarket wAPI Mod (stock_wapi)

An authentic virtual stock market mod for Minecraft 1.21.1 (NeoForge) where stock prices fluctuate in real-time based on AI-generated economic news and player supply and demand.
It features a bi-directional exchange mechanism between the unique currency "KABU" and any items, allowing anyone to easily enjoy trading stocks via sign UIs or commands.
All AI processing and data persistence are delegated to AI DataBase wAPI Core, allowing this mod to focus entirely on "stock market logic and game experience."

Item Value
Mod ID stock_wapi
Display Name StockMarket wapi mod
Versioning 1.21.1-x.y.z (MC Version-SemVer, independent of core)
Requirements aidbwapi_core required
License Apache License 2.0

🚀 Features & Architecture

1. AI-Driven Price Fluctuation System (Market Engine)

Stock prices are determined during periodic updates by summing the following four factors. The AI does not decide the price directly; it functions as one of the influential factors.

  • Internal Random Fluctuation: Natural price movement based on the base volatility set for each ticker.
  • Trend Tendency: Based on the initial tendency ("Bullish / Bearish / Neutral") set for each ticker, the trend dynamically changes with a certain probability (8%) during each periodic update, forming waves of prosperity and recession.
  • Player Supply & Demand Impact: Aggregates player buy and sell volumes during the update interval and reflects them in the price based on a logarithmic function: $log_{10}(1 + |netDemand|)$. This reflects the actions of market participants in the price while suppressing rapid fluctuations. The timing of demand reflection is at the "periodic update," and prices do not move instantly at the moment of trade.
  • AI Market Sentiment Impact: Market trend data is sent to the LLM via aidbwapi_core, and the "Market Sentiment Score (-N to +N)" returned by the AI is normalized and converted into price impact.

Price Safety Mechanisms

  • Stock prices are managed as integers. The fluctuation range per update is clamped to a maximum of ±10% (configurable via config).
  • Each ticker has a minimum price (minPrice) and a maximum price (maxPrice), and the price is always restricted within this range.
  • Rebound Mechanism: Near the minimum price, downward pressure is weakened and upward correction is strengthened to prevent the price from approaching zero. Bankruptcy or delisting does not occur.

Adaptive Demand Scaling (Adaptive Demand Scaling)

The total transaction volume of the server for the past 5 days (default: 120 updates) is saved as a moving average, which is used to automatically normalize the supply and demand impact. Even if the number of players or transaction scale changes, an appropriate balance is maintained without manual config adjustments.

2. AI News Generation (Market News)

During periodic updates, market trend data (fluctuation summaries for each ticker, world settings, etc.) is sent to aidbwapi_core, and the AI generates economic news text and market sentiment scores.

  • During periodic updates, news is broadcast to all players on the server in the format [StockWapi] via chat. If AI generation fails, fallback news ("Failed to retrieve AI market news due to a communication error. The market is moving solely based on technical factors.") is broadcast instead, and the market price update itself proceeds normally.
  • Latest news and past news history (up to 30 entries, with timestamps, newest first) can be viewed via /stockwapi news.
  • News history is kept indefinitely (stored in GlobalDB).

Behavior on AI Failure

If an AI request fails (e.g., all models unavailable), the stock price is calculated using only other factors with zero AI impact (sentiment=0). Fallback news is broadcast to all players.

For Admins: Troubleshooting AI Errors

  1. /dbwapi ai errors — Check recent error history (HTTP status codes/causes).
  2. /dbwapi model list — View status of all models (Enabled/Disabled, Penalty points).
  3. /dbwapi model enable <KeyName>.<ModelName> — Restore models automatically disabled due to authentication errors, etc.
  4. /dbwapi model reset <KeyName>.<ModelName> — Reset penalties and cooldowns.

3. AI Company Description Auto-Generation (Company Description)

When an admin adds a ticker, the ticker name is sent to aidbwapi_core, and the AI automatically generates a company description and saves it to the DB. This process is executed only at the time of registration.
If AI generation fails, a fallback description ("Company description is currently unavailable.") is automatically saved to the DB.
Players can view company descriptions via the /stockwapi info <ticker> command or signs.
To manually correct or replace a company description, directly edit the companyDesc_XXX key in the DB file (stock_wapi_GlobalDatabase.json).
Setting an existing company description to an empty string ("") and restarting the server will trigger the AI to automatically regenerate a new description.

4. Unique Currency "KABU" and Item Exchange (Currency & Exchange)

This mod does not depend on external economy mods and uses its own currency, "KABU".

  • Currency Name: KABU (Integer only, initial balance 0).
  • Balance & Transaction Limits: The maximum balance per player and the limit for a single transaction (including stock trades and item exchanges) is 2 billion KABU (2,000,000,000) (to prevent integer overflow and economic collapse).
  • Players can exchange any items (including vanilla and items from any mod) bi-directionally with KABU. Exchanges can be performed via Sign UI or commands.
  • Multiple items can be registered with different rates (e.g., Diamond = 100 KABU, Gold Ingot = 10 KABU). Registration of exchange targets is done via admin command (/stockwapi admin setrate), and rate information is saved in config/stock_wapi-exchange.json.

Item Exchange Safety Mechanisms

  1. Pre-Inventory Scan: To prevent partial consumption errors due to vanilla specifications, the player's entire inventory is scanned before the exchange process to check if the total amount possessed meets the required amount.
  2. Limit Overrun Block: If an exchange would cause the balance to exceed the limit (2 billion KABU), the process is completely blocked without consuming items.

5. Insider Trading Prevention & Market Integrity (Market Integrity)

To make trading before news disclosure structurally impossible, the update process is executed in the following strict order:

Lock Trading → Update Prices → Save News → Broadcast → Update Signs → Unlock Trading

If a trade is attempted during the lock, the player is notified that trading is currently blocked.

6. Commission System (Commission)

  • Commissions can be collected during buying and selling. Percentages can be set individually for buys and sells. Default is 0%.
  • Commission revenue can either "disappear (default)" or go to a "server-wide administrative account (configurable)". The admin account is not linked to any specific player UUID.
  • View the balance of the admin account with /stockwapi admin balance.

7. Sign Interface (Sign Interface)

By linking functions to sign blocks placed by an administrator, players can buy, sell, exchange, and view news with just a right-click.

  • Signs can only be placed by administrators (/stockwapi admin sign <type> [<arg1>] [<arg2>]).
  • Signs are automatically updated when stock prices update. Trading can be done directly from signs (executed instantly on right-click).
  • Signs cannot be destroyed by anyone other than an administrator (if an OP destroys one, it is automatically unlinked).

Sign Types (7 total)

Type Example Command Sign Display Right-Click Action
price sign price RDM Ticker + Price Display ticker details in chat
list sign list Market Header Display all tickers + prices in chat
buy sign buy RDM 5 Ticker + Qty + Price Instantly buy the specified quantity
sell sign sell RDM 5 Ticker + Qty + Price Instantly sell the specified quantity
exchange sign exchange diamond 10 Item + Qty + KABU Instant Item → KABU exchange
buyitem sign buyitem diamond 10 Item + Qty + KABU Instant KABU → Item purchase
news sign news News Header Display the latest news in chat

Unlinking: /stockwapi admin unsign (execute while looking at the sign)


💻 Requirements & Setup

  • Minecraft: 1.21.1
  • Mod Loader: NeoForge 21.1.219 or later
  • Java: Java 21 or higher
  • Required Dependency: aidbwapi_core (AI Communication & Database Foundation)
  • Side: Required on both Server and Client

Installation:

  1. Ensure aidbwapi_core is set up (AI provider registered and model configured).
  2. Place this mod (stock_wapi-x.x.x.jar) into the mods folder of your server or client and launch.
  3. Upon first launch, three demo preset tickers (RDM, END, OAK) will be automatically generated.

📖 Usage

Server Administrator: Initial Setup

Step 1: Preparing aidbwapi_core

Setup of aidbwapi_core is mandatory for this mod to function. Follow these steps:

1-1. Register AI Provider

Register connection information for your AI service (OpenAI-compatible API) as a "KeyName."

/dbwapi keyname add <KeyName> <API_Endpoint_URL> <API_Key>

⚠️ Security Warning: Due to Minecraft's specifications, the full command you type in chat (the plain text API key) will be recorded in the server's logs/latest.log.
For security, it is strongly recommended to edit config/aidbwapi_core-keynames.json directly with a text editor and then run /dbwapi reload in-game.

1-2. Register Model

Add the AI model you wish to use to the registered provider.

/dbwapi model add <KeyName>.<ModelName> <DailyLimit> <MinuteLimit>

If limits are omitted or set to -1, they are registered as unlimited. Registering multiple providers/models allows the system to automatically switch if one fails (failover).

1-3. Verify Operation
/dbwapi ai test

If you receive a response from the AI, the setup is complete. If an error occurs, check the details with /dbwapi ai errors.

Step 2: First Launch & Auto Setup

After placing this mod in the mods folder and starting the server, the following will happen:

  • Three demo preset tickers (RDM, END, OAK) will be defined in config/stock_wapi-stocks.json.
  • AI company descriptions for each ticker will be asynchronously generated and saved.
  • The periodic market update scheduler will start (Default: every 1 hour).

Step 3: Register Item Exchange Rates

Set up exchange rates so players can obtain KABU.

/stockwapi admin setrate diamond 100
/stockwapi admin setrate gold_ingot 10

This enables exchanges like "1 Diamond = 100 KABU" and "1 Gold Ingot = 10 KABU."

Step 4: Placing Signs (Optional)

Set up Sign UIs so players can interact with a right-click. Place a sign and execute the following commands while looking at it:

/stockwapi admin sign price RDM             ← Displays RDM price
/stockwapi admin sign buy RDM 5             ← Buys 5 shares of RDM
/stockwapi admin sign sell RDM 5            ← Sells 5 shares of RDM
/stockwapi admin sign exchange diamond 10   ← Exchange 10 Diamonds for KABU
/stockwapi admin sign buyitem diamond 1     ← Purchase 1 Diamond with KABU
/stockwapi admin sign list                  ← Displays all tickers
/stockwapi admin sign news                  ← Displays latest news

Step 5: Adding/Customizing Tickers (Optional)

To add a custom ticker:

/stockwapi admin add ABC "Alpha Beta Corp" 50000

The ticker definition will be appended to config/stock_wapi-stocks.json. To fine-tune volatility, trend, or market type, edit this JSON file directly while the server is stopped.

Player: Basic Gameplay

1. Obtaining KABU

First, obtain KABU via item exchange.

/stockwapi exchange diamond 10

(If the admin has set up signs, you can exchange instantly by right-clicking.)

2. Researching Tickers

/stockwapi list                ← View current prices for all tickers
/stockwapi info RDM            ← View detailed info for RDM
/stockwapi news                ← View the latest AI-generated economic news

3. Trading Stocks

/stockwapi buy RDM 10          ← Buy 10 shares of RDM
/stockwapi sell RDM 5           ← Sell 5 shares of RDM

Upon trade completion, detailed information (ticker, quantity, unit price, total, commission, payment/receipt, shares owned, average cost) is displayed in chat.

4. Checking Assets

/stockwapi myinfo              ← View balance, holdings, and P&L

5. Converting KABU Back to Items

If you make a profit, you can spend KABU to purchase items (like Diamonds).

/stockwapi buyitem diamond 1        ← Pay KABU to obtain 1 Diamond

Operation Tips

  • Market Pause: Use /stockwapi admin pause during maintenance to stop all trading and periodic updates. Resume with /stockwapi admin resume.
  • Removing Tickers: Use /stockwapi admin remove ABC <Your_UUID> to remove a ticker. If there are holders, their shares will be forcibly liquidated at the current price. Your UUID is required to prevent accidental deletion.
  • Using Commissions: To suppress speculative large-scale trading, set buyFeePercent / sellFeePercent in the TOML config. Set feeToAdminAccount = true to pool commissions in the admin account.

⚙️ Configuration & Directory Structure

  • config/stock_wapi-common.toml : Basic settings for the entire mod.

    [general] Section:

    • commandPermissionLevel: Required OP level for admin commands (Default: 2).
    • debugLogging: Enable debug logs (Default: false). Usually not needed.

    [market] Section:

    • updatesPerDay: Number of market updates per day (Default: 24, every 1 hour real-time).
    • maxPriceChangePercent: Max fluctuation per update (Default: 10, ±10%).
    • tradingPausedOnUpdate: Pause trading during update processing (Default: true). If false, the insider trading lock mechanism is disabled.

    [trading] Section:

    • buyFeePercent / sellFeePercent: Commission rates for buying and selling (Default: 0).
    • feeToAdminAccount: Whether to pool commissions in the admin account (Default: false, disappear).
    • allowShortSelling: Flag for short selling (Config exists, but currently unimplemented; setting to true has no effect).
    • minTradeUnit: Minimum trading unit (Default: 1).
    • maxTradeAmount: Maximum trading amount per trade (Default: -1, unlimited).
    • maxHoldingPerPlayer: Maximum holdings per ticker per player (Default: -1, unlimited).

    [ai] Section:

    • sentimentScoreRange: Range of AI sentiment score (Default: 100, -100 to +100).
    • newsLanguage: Language for AI-generated news (Default: ja).
    • worldSetting: Text describing the world setting passed to the AI (Default: "A fictional stock market in the Minecraft world").
  • config/stock_wapi-stocks.json : Definition file for all ticker parameters (stored as an array).
    Definitions are auto-appended with default values when using the add command. To fine-tune parameters other than initial price (volatility, trend, rebound strength, market type, etc.), edit this file while the server is stopped.

    {
      "ticker": "RDM",
      "name": "Redstone Dynamics Mining",
      "initialPrice": 15000,
      "volatility": 0.03,
      "stability": 0.9,
      "trend": "neutral",
      "marketType": "stable",
      "minPrice": 1000,
      "maxPrice": 100000,
      "reboundStrength": 0.1,
      "tradeImpactFactor": 0.4,
      "aiImpactFactor": 0.05,
      "description": ""
    }
    
  • config/stock_wapi-exchange.json : Saved file for item exchange rates.
    Stores rate info registered via admin command (/stockwapi admin setrate).

  • [World Save Root]/aidbwapi_core/stock_wapi/ : Storage for operational data (uses aidbwapi_core category DB).

    • global.json: Current prices, price history (full), news history, sentiment values, demand aggregate data, update counters, volume moving average history, etc.
    • players/<UUID>.json: Per-player KABU balance, shares owned, average purchase cost, and trade history.

🛠️ Command Reference

All commands start with /stockwapi.
Ticker symbols are used to specify stocks, but inputting them in lowercase will automatically convert them to uppercase internally.
<ticker> and <item> arguments support Tab completion.

📌 Player Commands (No permission required)

Command Description
/stockwapi list List tickers and current prices for all stocks
/stockwapi info <ticker> View detailed ticker info (Price, Market Type, Demand, Description)
/stockwapi myinfo View your KABU balance, holdings, and P&L
/stockwapi portfolio Synonym for myinfo (Alias)
/stockwapi buy <ticker> <quantity> Purchase specified quantity of a ticker (instantly filled at current price)
/stockwapi sell <ticker> <quantity> Sell specified quantity of a ticker (instantly filled at current price)
/stockwapi news View latest market news + past news history (up to 30 entries)
/stockwapi exchange <item> <count> Exchange specified item for KABU
/stockwapi buyitem <item> <count> Purchase specified item using KABU

📌 Administrator Commands (OP required, default permission level 2)

Command Description
/stockwapi admin add <ticker> <name> <initialPrice> Register and initialize a new ticker. Auto-generates AI company description. Fine-tune parameters in the generated JSON
/stockwapi admin remove <ticker> <executorUUID> Remove a ticker. Requires executor's UUID to prevent accidental deletion. Forcibly liquidates shares for holders
/stockwapi admin pause Pause all market trades and periodic updates
/stockwapi admin resume Resume all market trades and periodic updates
/stockwapi admin balance View the balance of the admin account (pool for commissions)
/stockwapi admin setrate <item> <kabuRate> Add or update an item exchange rate (e.g., diamond 100)
/stockwapi admin removerate <item> Remove an item exchange rate
/stockwapi admin listrates List all item exchange rates
/stockwapi admin sign <type> [<arg1>] [<arg2>] Link a function to a sign block (execute while looking at sign). Arguments vary by type
/stockwapi admin unsign Unlink a function from a sign block (execute while looking at sign)

🏗️ Internal Architecture Supplemental

Market Update Scheduler

The timer itself runs on a daemon thread of ScheduledExecutorService, but to ensure database access and state change safety, the actual update processing is always synchronized with the main server thread (MinecraftServer.execute()).
The update timer is based on real-time and resumes from where it left off upon server restart.

Trade Result Handling (TradeResult Enum)

To prevent command logic from becoming overly complex, internal trade processing results are returned as an Enum (TradeResult) with over 10 states (Success, Insufficient Balance, Insufficient Shares, Ticker Not Registered, Market Locked for Update, etc.). Warning messages for players are also managed centrally by this Enum.

DB Structure (Using aidbwapi_core Category DB)

  • Category Name: stock_wapi
  • GlobalDatabase: Current prices, price history (full), sentiment values, news history, demand aggregate data, update counter, volume moving average history (volumeHistory).
  • PlayerDatabase: KABU balance (balance), shares owned (holdings), average purchase prices (avgPrices), trade history (tradeHistory).

Thread Safety for Asynchronous Processing

DB access from asynchronous threads, such as the callback for AI company description generation, is delegated to the main thread via MinecraftServer.execute() to guarantee thread safety.


⚖️ License (License)

The source code and provided binaries of this mod are provided and published under the Apache License, Version 2.0.
Creation and redistribution of commercial or non-commercial mods that use or modify this mod are permitted freely within the scope of the license terms.

StockMarket wAPI Mod (stock_wapi)

Minecraft 1.21.1 (NeoForge) 向けの、AIが生成する経済ニュースとプレイヤーの需給によって株価がリアルタイムに変動する本格派の仮想株式市場Modです。
独自通貨「KABU」と任意のアイテムとの双方向交換機構を備え、看板UIやコマンドを通じて誰でも手軽に株の売買を楽しめます。
AI処理およびデータ永続化はすべて AI DataBase wAPI Core に委譲しており、本Modは「株式ロジックとゲーム体験」のみを担当します。

項目
Mod ID stock_wapi
表示名 StockMarket wapi mod
バージョン体系 1.21.1-x.y.z(MC版-SemVer、coreとは独立)
導入要件 ** aidbwapi_core 必須**
ライセンス Apache License 2.0

🚀 コア機能とアーキテクチャ (Features & Architecture)

1. AI駆動の株価変動システム (Market Engine)

株価は以下の4つの要素を合算して定期更新時に決定されます。AIは価格を直接決定せず、あくまで影響要素の一つとして機能します。

  • 内部ランダム変動: 銘柄ごとに設定された基本ボラティリティに基づく自然な価格変動。
  • トレンド傾向: 銘柄ごとに設定された「上昇寄り/下降寄り/中立」の初期傾向をもとに、毎回の定期更新時に一定確率(8%)でトレンドが動的に変化し、好景気・不景気の波を形成します。
  • プレイヤー需給影響: 更新間隔中のプレイヤーの買い・売り数量を集計し、対数関数 (log10(1 + |netDemand|)) をベースに価格へ反映。急激な変動を抑制しつつ、市場参加者の行動が価格に影響を与えます。需給の反映タイミングは「定期更新時」であり、売買した瞬間に即座に株価が動くわけではありません。
  • AI市場心理影響: aidbwapi_core 経由でLLMに市場動向データを送信し、AIが返す「市場心理スコア(-N〜+N)」を正規化して価格影響に変換します。

価格の安全装置

  • 株価は整数で管理。1回の更新あたりの変動幅は最大±10%(config変更可能)にクランプされます。
  • 各銘柄には最低価格(minPrice)と最高価格(maxPrice)が設定され、価格は常にこの範囲内に制限されます。
  • リバウンド機構: 最低価格付近では下落圧力を弱め、上昇補正を強めることで価格が0に近づくことを防ぎます。倒産・上場廃止は発生しません。

自動スケール適応 (Adaptive Demand Scaling)

サーバーの過去5日分(デフォルト120回分)の総取引量を移動平均として保存し、これを用いて需給影響を自動で正規化します。プレイヤー人数や取引規模が変化しても、手動でのconfig調整なしで適切なバランスが維持されます。

2. AIニュース生成 (Market News)

定期更新時に aidbwapi_core へ市場動向データ(各銘柄の変動概要、世界観設定等)を送信し、AIが経済ニュース文と市場心理スコアを生成します。

  • 定期更新時、サーバー内の全プレイヤーに [StockWapi] の形式でニュースをチャットへブロードキャストします。AI生成が失敗した場合は、フォールバックニュース(「通信障害によりAI市場ニュースの取得に失敗しました。市場はテクニカルな要因のみで動いています。」)が代わりにブロードキャストされ、市場価格の更新自体は正常に行われます。
  • /stockwapi news で最新ニュース+過去ニュース履歴(最大30件、タイムスタンプ付き、新しい順)を閲覧可能。
  • ニュース履歴は無期限保持(GlobalDBに保存)。

AI失敗時の挙動

AIリクエストが失敗した場合(全モデル不可等)は、AI影響ゼロ(sentiment=0)で他の要素のみで株価を計算します。フォールバックニュースが全プレイヤーにブロードキャストされます。

管理者向け: AIエラー発生時の確認手順

  1. /dbwapi ai errors — 直近のエラー履歴(HTTPステータスコード・原因)を確認
  2. /dbwapi model list — 全モデルの状態(有効/無効、ペナルティ値)を一覧確認
  3. /dbwapi model enable <登録名>.<モデル名> — 認証エラー等で自動無効化されたモデルを復帰
  4. /dbwapi model reset <登録名>.<モデル名> — ペナルティ・クールダウンをリセット

3. AI企業説明自動生成 (Company Description)

管理者が銘柄を追加すると、銘柄名を aidbwapi_core へ送信し、AIが企業説明文を自動生成してDBへ保存します。この処理は登録時のみ実行されます。
AI生成が失敗した場合は、フォールバック説明文(「現在、企業説明は取得できません。」)がDBに自動保存されます。
プレイヤーは /stockwapi info <ticker> コマンドや看板から企業説明を閲覧できます。
管理者が企業説明を手動で修正・差し替える場合は、DBファイル(stock_wapi_GlobalDatabase.json)の companyDesc_XXX キーを直接編集してください。
既存の企業説明を空文字("")にしてサーバーを再起動すると、AIが新しい説明を自動再生成します。

4. 独自通貨「KABU」とアイテム交換 (Currency & Exchange)

本Modは外部の経済Modに依存せず、独自通貨「KABU」を使用します。

  • 通貨名称: KABU(整数のみ、初期所持0)
  • 残高・取引上限: 1プレイヤーの所持金上限、および1回の全取引(株の売買・アイテム交換などすべて含む)の上限は 20億 KABU (2,000,000,000)。(整数オーバーフローおよび経済バランス崩壊防止のため)
  • プレイヤーは任意のアイテム(バニラ含む、どのModのアイテムでも可)とKABUを双方向に交換できます。交換は看板UIやコマンドから実行可能です。
  • 複数のアイテムをそれぞれ異なるレートで登録可能(例: ダイヤ=100KABU、金インゴット=10KABU)。交換対象の登録は管理者コマンド (/stockwapi admin setrate) で行い、レート情報は config/stock_wapi-exchange.json に保存されます。

アイテム交換の安全機構

  1. 事前インベントリスキャン: バニラ仕様による部分消費エラーを防ぐため、交換処理前にプレイヤーのインベントリ全体をスキャンし、所持総量が要求量に達しているかを事前チェック。
  2. 上限超過ブロック: 交換によって所持金が上限(20億KABU)を超える場合は、アイテムを消費せず処理を完全にブロック。

5. インサイダー対策と市場の公正性 (Market Integrity)

ニュース公開前の取引を構造的に不可能にするため、更新処理は以下の厳格な順序で実行されます。

売買ロック → 価格更新 → ニュース保存 → 配信 → 看板更新 → ロック解除

ロック中に売買を試みた場合は、ブロックされている旨がプレイヤーに通知されます。

6. 手数料システム (Commission)

  • 売買時に手数料を徴収可能。買い・売りそれぞれ個別にパーセンテージで設定。デフォルトは0%。
  • 手数料収益の行き先は「消滅(デフォルト)」または「サーバー全体の管理口座(config変更可能)」。管理口座は特定プレイヤーUUIDに紐づきません。
  • /stockwapi admin balance で管理口座の残高を確認できます。

7. 看板UI (Sign Interface)

管理者が設置した看板ブロックに機能を紐付けることで、プレイヤーは右クリックだけで売買・換金・ニュース閲覧が可能になります。

  • 設置は管理者のみ可能(/stockwapi admin sign <type> [<arg1>] [<arg2>])。
  • 株価更新時に自動更新。看板から直接売買も可能(右クリックで即時実行)。
  • 管理者以外は破壊不可(OPが破壊した場合は自動登録解除)。

看板の種類(全7種)

種類 設置コマンド例 看板表示 右クリック動作
price sign price RDM 銘柄名+価格 銘柄詳細をチャットに表示
list sign list 銘柄一覧ヘッダ 全銘柄+価格をチャットに表示
buy sign buy RDM 5 銘柄+数量+価格 指定数量を即時購入
sell sign sell RDM 5 銘柄+数量+価格 指定数量を即時売却
exchange sign exchange diamond 10 アイテム名+数量+KABU額 アイテム→KABU即時交換
buyitem sign buyitem diamond 10 アイテム名+数量+KABU額 KABU→アイテム即時購入
news sign news 最新ニュースヘッダ 最新ニュース1件をチャットに表示(コマンド版は30件履歴付き)

登録解除: /stockwapi admin unsign(管理者が看板を見ながら実行)


💻 動作要件とインストール (Requirements & Setup)

  • Minecraft: 1.21.1
  • Mod Loader: NeoForge 21.1.219 以降
  • Java: Java 21 以上
  • 必須依存Mod: aidbwapi_core(AI通信・データベース基盤)
  • サイド: サーバー・クライアント両方必須

インストール:

  1. aidbwapi_core のセットアップが完了していること(AIプロバイダの登録・モデルの設定済み)を確認してください。
  2. 当Mod (stock_wapi-x.x.x.jar) をサーバーまたはクライアントの mods フォルダに配置して起動します。
  3. 初回起動時、デモ用のプリセット3銘柄(RDM, END, OAK)が自動生成されます。

📖 使用方法 (Usage)

サーバー管理者: 初期セットアップ

Step 1: aidbwapi_core の準備

本Modの動作には aidbwapi_core のセットアップが必須です。以下の手順で完了してください。

1-1. AIプロバイダの登録

AIサービス(OpenAI互換API)の接続情報を「登録名(KeyName)」として登録します。

/dbwapi keyname add <登録名> <APIエンドポイントURL> <APIキー>

⚠️ セキュリティ警告: Minecraftの仕様上、チャット欄に入力したコマンド全文(APIキーの平文)はサーバーの logs/latest.log にそのまま記録されます。
安全のため、config/aidbwapi_core-keynames.json をテキストエディタで直接編集し、ゲーム内で /dbwapi reload を実行する運用を強く推奨します。

1-2. モデルの登録

登録したプロバイダに、使用するAIモデルを追加します。

/dbwapi model add <登録名>.<モデル名> <日次上限> <分次上限>

上限値を省略または -1 にすると無制限として登録されます。
複数のプロバイダ・モデルを登録すると、障害時に自動で次のモデルへ切り替わります(フェイルオーバー)。

1-3. 動作確認
/dbwapi ai test

AIからの応答が返ってくれば準備完了です。エラーが出る場合は /dbwapi ai errors でエラー内容を確認してください。

Step 2: 初回起動と自動セットアップ

本Modを mods フォルダに配置してサーバーを起動すると、以下が自動的に行われます。

  • デモ用プリセット3銘柄(RDM, END, OAK)の定義が config/stock_wapi-stocks.json に生成
  • 各銘柄のAI企業説明が非同期で自動生成・保存
  • 市場の定期更新スケジューラが開始(デフォルト: 1時間ごと)

Step 3: アイテム交換レートの登録

プレイヤーがKABUを入手する手段として、アイテム交換レートを設定してください。

/stockwapi admin setrate diamond 100
/stockwapi admin setrate gold_ingot 10

これにより「ダイヤ1個 = 100 KABU」「金インゴット1個 = 10 KABU」で交換可能になります。

Step 4: 看板の設置(任意)

プレイヤーが右クリックだけで操作できるよう、看板UIを設置できます。
看板ブロックを設置し、それを見ながら以下のコマンドを実行してください。

/stockwapi admin sign price RDM       ← RDMの価格表示看板
/stockwapi admin sign buy RDM 5       ← RDMを5株購入する看板
/stockwapi admin sign sell RDM 5      ← RDMを5株売却する看板
/stockwapi admin sign exchange diamond 10  ← ダイヤ10個→KABU換金の看板
/stockwapi admin sign buyitem diamond 1   ← KABUでダイヤ1個を購入する看板
/stockwapi admin sign list            ← 全銘柄一覧の看板
/stockwapi admin sign news            ← 最新ニュースの看板

Step 5: 銘柄の追加・カスタマイズ(任意)

独自の銘柄を追加する場合:

/stockwapi admin add ABC "Alpha Beta Corp" 50000

追加後、config/stock_wapi-stocks.json に銘柄定義が追記されます。
ボラティリティや市場タイプなどを細かく調整したい場合は、このJSONファイルをサーバー停止時に直接編集してください。

プレイヤー: 基本的な遊び方

1. KABUを手に入れる

まずはアイテム交換でKABUを入手しましょう。

/stockwapi exchange diamond 10

(管理者が設定した看板がある場合は、右クリックで即時交換も可能)

2. 銘柄を調べる

/stockwapi list                ← 全銘柄の現在価格を確認
/stockwapi info RDM            ← RDMの詳細情報を確認
/stockwapi news                ← AIが生成した最新の経済ニュースを確認

3. 株を売買する

/stockwapi buy RDM 10          ← RDMを10株購入
/stockwapi sell RDM 5           ← RDMを5株売却

売買完了時には、銘柄名・数量・単価・合計額・手数料・支払/受取額・保有数・平均取得価格が詳細にチャット表示されます。

4. 自分の資産を確認する

/stockwapi myinfo              ← 残高・保有銘柄・損益を一覧表示

5. KABUをアイテムに戻す

利益が出たら、KABUを消費してアイテム(ダイヤモンド等)を購入できます。

/stockwapi buyitem diamond 1        ← KABUを支払ってダイヤ1個を入手

運用Tips

  • 市場の一時停止: メンテナンス時などは /stockwapi admin pause で売買と定期更新を一括停止できます。再開は /stockwapi admin resume
  • 銘柄の削除: /stockwapi admin remove ABC <あなたのUUID> で銘柄を削除できます。保有者がいる場合は現在価格で強制清算されます。誤操作防止のため、あなた自身のUUIDの入力が必須です。
  • 手数料の活用: 投機的な大量売買を抑制したい場合は、TOML設定で buyFeePercent / sellFeePercent を設定してください。feeToAdminAccount = true にすると手数料が管理口座にプールされます。

⚙️ 設定ファイルとディレクトリ構造 (Configuration)

  • config/stock_wapi-common.toml : Mod全体の基礎動作設定ファイル。

    [general] セクション:

    • commandPermissionLevel: 管理者コマンドの要求OP権限レベル(デフォルト 2)。
    • debugLogging: デバッグログの有効化(デフォルト false)。通常は変更不要。

    [market] セクション:

    • updatesPerDay: 1日の市場更新回数(デフォルト 24、リアルタイム1時間ごと)。
    • maxPriceChangePercent: 1回の更新あたりの最大変動幅(デフォルト 10、±10%)。
    • tradingPausedOnUpdate: 更新処理中に売買を一時停止するか(デフォルト true)。false にするとインサイダー対策のロック機構が無効化されます。

    [trading] セクション:

    • buyFeePercent / sellFeePercent: 買い・売りの手数料率(デフォルト 0)。
    • feeToAdminAccount: 手数料を管理口座にプールするか(デフォルト false、消滅)。
    • allowShortSelling: 空売りの許可フラグ(Config項目として存在するが、現在未実装のため、trueにしても動作しない)。
    • minTradeUnit: 最低売買単位(デフォルト 1)。
    • maxTradeAmount: 1回の最大売買数(デフォルト -1、無制限)。
    • maxHoldingPerPlayer: 1プレイヤーの銘柄別保有上限(デフォルト -1、無制限)。

    [ai] セクション:

    • sentimentScoreRange: AI心理スコアの範囲(デフォルト 100、-100〜+100)。
    • newsLanguage: AIが生成するニュースの言語(デフォルト ja)。
    • worldSetting: AIに渡す世界観設定テキスト(デフォルト "Minecraft世界の架空企業の株式市場")。
  • config/stock_wapi-stocks.json : 全銘柄の詳細パラメータ定義ファイル(1ファイルに配列として格納)。
    銘柄追加コマンド実行時にデフォルト値で自動追記されます。初期価格以外のパラメータ(ボラティリティ、トレンド、リバウンド強度、市場タイプ等)を細かく調整したい場合は、サーバー停止時にこのファイルを直接編集してください。

    {
      "ticker": "RDM",
      "name": "Redstone Dynamics Mining",
      "initialPrice": 15000,
      "volatility": 0.03,
      "stability": 0.9,
      "trend": "neutral",
      "marketType": "stable",
      "minPrice": 1000,
      "maxPrice": 100000,
      "reboundStrength": 0.1,
      "tradeImpactFactor": 0.4,
      "aiImpactFactor": 0.05,
      "description": ""
    }
    
  • config/stock_wapi-exchange.json : アイテム交換レートの保存ファイル。
    管理者コマンド (/stockwapi admin setrate) で登録されたレート情報が保存されます。

  • [ワールド保存ルート]/aidbwapi_core/stock_wapi/ : 運用データの保存先(aidbwapi_core のカテゴリDB機構を使用)。

    • global.json: 現在価格、価格履歴、ニュース履歴、市場心理値、需給集計データ、更新回数カウンタ、取引量の移動平均履歴等。
    • players/<UUID>.json: プレイヤーごとのKABU残高、保有株数、平均取得価格、売買履歴。

🛠️ コマンドリファレンス (Command Reference)

すべてのコマンドは /stockwapi で始まります。
銘柄の指定にはティッカーシンボルを使用しますが、小文字で入力しても内部で自動的に大文字に変換されて処理されます。
<ticker> および <item> 引数はTab補完に対応しています。

📌 プレイヤーコマンド(権限不要)

コマンド 説明
/stockwapi list 全銘柄のティッカーと現在価格を一覧表示
/stockwapi info <ticker> 銘柄の詳細情報(価格、市場タイプ、需給、企業説明)を表示
/stockwapi myinfo 自分のKABU残高と保有銘柄・損益を一覧表示
/stockwapi portfolio myinfo と同義(エイリアス)
/stockwapi buy <ticker> <quantity> 指定銘柄を指定数量購入(現在価格で即時約定)
/stockwapi sell <ticker> <quantity> 指定銘柄を指定数量売却(現在価格で即時約定)
/stockwapi news 最新の市場ニュース+過去ニュース履歴(最大30件)を表示
/stockwapi exchange <item> <count> 指定アイテムをKABUに換金
/stockwapi buyitem <item> <count> KABUで指定アイテムを購入

📌 管理者コマンド(OP権限必須、デフォルト permission level 2)

コマンド 説明
/stockwapi admin add <ticker> <name> <initialPrice> 新規銘柄を登録・初期化。AI企業説明を自動生成。詳細パラメータは生成されたJSONファイルで調整可能
/stockwapi admin remove <ticker> <executorUUID> 銘柄を削除。誤削除防止のため実行者UUID必須。保有者には強制清算(現在価格で自動売却しKABUを返却)を実施
/stockwapi admin pause 市場の取引および定期更新を一時停止
/stockwapi admin resume 市場の取引および定期更新を再開
/stockwapi admin balance 管理口座(売買手数料のプール先)の残高を確認
/stockwapi admin setrate <item> <kabuRate> アイテムの交換レートを追加または更新(例: diamond 100
/stockwapi admin removerate <item> アイテムの交換レートを削除
/stockwapi admin listrates 全アイテム交換レートを一覧表示
/stockwapi admin sign <type> [<arg1>] [<arg2>] 看板ブロックに機能を紐付ける(看板を見ながら実行)。引数は type により可変
/stockwapi admin unsign 看板ブロックの機能登録を解除(看板を見ながら実行)

🏗️ 内部アーキテクチャ補足 (Internal Architecture)

市場更新スケジューラ

タイマー自体は ScheduledExecutorService のデーモンスレッドで稼働しますが、データベースアクセスや状態変更の安全性を確保するため、実際の更新処理は必ずメインサーバースレッド (MinecraftServer.execute()) に同期して実行されます。
更新タイマーはリアルタイム基準で、サーバー再起動時は前回の続きから再開します。

売買結果処理 (TradeResult Enum)

コマンド処理の複雑化を防ぐため、内部の売買処理結果は10種類以上の状態(成功、残高不足、保有数不足、銘柄未登録、市場更新中によるロックなど)を持つ Enum (TradeResult) で返し、プレイヤーへの警告メッセージもこの Enum が一元管理します。

DB構造 (aidbwapi_core カテゴリDB使用)

  • カテゴリ名: stock_wapi
  • GlobalDatabase: 現在価格、価格履歴(全履歴)、市場心理値、ニュース履歴、需給集計データ、更新回数カウンタ、取引量の移動平均履歴 (volumeHistory)。
  • PlayerDatabase: KABU残高 (balance)、保有株数 (holdings)、平均取得価格 (avgPrices)、売買履歴 (tradeHistory)。

非同期処理のスレッドセーフティ

AI企業説明の非同期生成コールバックなど、非同期スレッドからのDBアクセスは MinecraftServer.execute() を経由してメインスレッドに委譲し、スレッドセーフを保証しています。


⚖️ ライセンス (License)

このModのソースコードおよび提供されるバイナリは Apache License, Version 2.0 で提供・公開されています。
本Modを利用・改変した商用・非商用Modの作成および再配布は、ライセンス条項の範囲内で自由に行っていただけます。

Available Versions

StockMarket wAPI 1.21.1-0.1.2release
MC 1.21.1neoforge
March 4, 2026
StockMarket wAPI 1.21.1-0.1.0release
MC 1.21.1neoforge
March 3, 2026

How to Install StockMarket wAPI on Your Server

1

Order Server

Order a Minecraft Java server with at least 3 GB RAM (4 GB recommended).

2

Set neoforge Loader

In the panel under "Egg", select the neoforge loader and matching Minecraft version (1.21.1).

3

Install Mod

Open the mod browser in the dashboard and search for "StockMarket wAPI". Click "Install" – done! Alternatively, upload the .jar via SFTP to the /mods folder.

Compatibility

Mod Loaders

neoforge

Minecraft Versions

1.21.1

Server-side

Required

Recommended RAM

4 GB(min. 3 GB)

Frequently Asked Questions

StockMarket wAPI server crashes on startup – what to do?

Most common cause: wrong neoforge version or insufficient RAM. Check the server log (latest.log) for "OutOfMemoryError" or "Mixin" errors. With Mado Hosting: ensure at least 3 GB RAM is allocated and the loader matches the mod version (1.21.1). You can switch loaders with one click in the panel.

Is StockMarket wAPI compatible with neoforge?

StockMarket wAPI officially supports neoforge for Minecraft 1.21.1. The Mado dashboard automatically detects incompatible loader combinations.

Server lagging with StockMarket wAPI – how to optimize performance?

Recommended RAM: 4 GB (per 8 players). Use /spark profiler to check if StockMarket wAPI consumes the most tick time. Common fixes: reduce server view-distance to 8-10, install "performant" or "starlight" as supplementary mods on Forge. With Mado Hosting, your server runs on NVMe SSDs with dedicated CPU cores for minimal latency.

Rent Modded Server

Install StockMarket wAPI with just one click on your server.

Recommended RAM
4 GBab €8/mo
Min. 3 GB | +1 GB pro 8 Spieler
Create Server Now
1-Click Mod Install
NVMe SSD Storage
DDoS Protection included

Details

License
Apache License 2.0
Server-side
Required

Supported Versions

1.21.1