Field Manual Brokerage / Linux / Laravel

PASTE IN BUILD ORDER

Assemble project

Complete files from your brokerage practice project. Start with the Linux setup. These are a prepared implementation with provisional API assumptions; adapt them to the actual task. Laravel 11/12 bootstrap style. No npm or frontend build.

Fresh skeleton: run the block below from the directory containing artisan. It overwrites the listed files. It does not install dependencies, copy .env, generate a key or migrate; finish those steps in the runbook. Supplied project: use individual files and merge configuration, routing, bootstrap and test setup. Do not paste a second orders migration.

Copy all files — fresh skeleton only
mkdir -p '.'
cat > '.env.example' <<'BROKERAGE_REFERENCE_EOF'
APP_NAME="Brokerage Market"
APP_ENV=local
APP_KEY=
APP_DEBUG=false
APP_URL=http://localhost:8000

LOG_CHANNEL=single
DB_CONNECTION=sqlite
SESSION_DRIVER=file
CACHE_STORE=file

EXCHANGE_DEMO=true
EXCHANGE_BASE_URL=
EXCHANGE_API_KEY=
BROKERAGE_REFERENCE_EOF

mkdir -p 'config'
cat > 'config/services.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

return [
    'exchange' => [
        'base_url' => env('EXCHANGE_BASE_URL', ''),
        'api_key' => env('EXCHANGE_API_KEY', ''),
        'demo' => (bool) env('EXCHANGE_DEMO', true),
    ],
];
BROKERAGE_REFERENCE_EOF

mkdir -p 'database/migrations'
cat > 'database/migrations/2026_01_01_000000_create_orders_table.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class () extends Migration {
    public function up(): void
    {
        Schema::create('orders', function (Blueprint $table): void {
            $table->id();
            $table->uuid('client_order_id')->unique();
            $table->string('exchange_order_id')->nullable()->unique();
            $table->string('symbol');
            $table->string('side');
            $table->string('type');
            $table->unsignedInteger('quantity');
            $table->decimal('price', 12, 4)->nullable();
            $table->string('status')->default('pending');
            $table->text('rejection_message')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('orders');
    }
};
BROKERAGE_REFERENCE_EOF

mkdir -p 'app/Models'
cat > 'app/Models/Order.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $fillable = [
        'client_order_id', 'exchange_order_id', 'symbol', 'side', 'type',
        'quantity', 'price', 'status', 'rejection_message',
    ];

    protected function casts(): array
    {
        return ['quantity' => 'integer', 'price' => 'decimal:4'];
    }
}
BROKERAGE_REFERENCE_EOF

mkdir -p 'app/Exceptions'
cat > 'app/Exceptions/ExchangeException.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

namespace App\Exceptions;

use RuntimeException;

class ExchangeException extends RuntimeException
{
    public function __construct(string $message, public readonly int $httpStatus)
    {
        parent::__construct($message);
    }
}
BROKERAGE_REFERENCE_EOF

mkdir -p 'app/Services'
cat > 'app/Services/ExchangeClient.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

namespace App\Services;

use App\Exceptions\ExchangeException;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class ExchangeClient
{
    public function marketData(): array
    {
        if (config('services.exchange.demo')) {
            return json_decode(file_get_contents(resource_path('data/market.json')), true, flags: JSON_THROW_ON_ERROR);
        }

        return $this->request('GET', '/v1/market-data');
    }

    public function submitOrder(array $payload): array
    {
        if (config('services.exchange.demo')) {
            return [
                'exchange_order_id' => 'DEMO-'.$payload['client_order_id'],
                'client_order_id' => $payload['client_order_id'],
                'status' => 'accepted',
            ];
        }

        return $this->request('POST', '/v1/orders', $payload);
    }

    private function request(string $method, string $path, array $payload = []): array
    {
        try {
            $response = Http::withToken(config('services.exchange.api_key'))
                ->baseUrl(config('services.exchange.base_url'))
                ->acceptJson()
                ->asJson()
                ->timeout(5)
                ->connectTimeout(2)
                ->send($method, $path, $method === 'POST' ? ['json' => $payload] : []);
        } catch (ConnectionException $exception) {
            Log::warning('Exchange connection failed', ['path' => $path]);
            throw new ExchangeException('The exchange is temporarily unavailable.', 503);
        }

        if (!$response->successful()) {
            Log::warning('Exchange request failed', ['path' => $path, 'status' => $response->status()]);
            if ($method === 'POST' && $response->clientError()) {
                throw new ExchangeException('The exchange rejected the order. Please check your order details.', 422);
            }
            throw new ExchangeException('The exchange is temporarily unavailable.', 503);
        }

        $data = $response->json();
        $valid = is_array($data) && ($method === 'GET'
            ? isset($data['data']) && is_array($data['data'])
            : is_string($data['exchange_order_id'] ?? null) && ($data['status'] ?? null) === 'accepted');
        if (!$valid) {
            Log::warning('Exchange returned an unexpected response', ['path' => $path]);
            throw new ExchangeException('The exchange returned an unexpected response.', 503);
        }

        return $data;
    }
}
BROKERAGE_REFERENCE_EOF

mkdir -p 'app/Http/Requests'
cat > 'app/Http/Requests/StoreOrderRequest.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreOrderRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'symbol' => ['required', 'string', 'regex:/^[A-Z]{1,5}$/'],
            'side' => ['required', 'in:buy,sell'],
            'type' => ['required', 'in:limit,market'],
            'quantity' => ['required', 'integer', 'min:1', 'max:1000000'],
            'price' => ['exclude_if:type,market', 'required_if:type,limit', 'nullable', 'numeric', 'gt:0', 'decimal:0,4', 'max:99999999.9999'],
        ];
    }

    public function messages(): array
    {
        return [
            'symbol.required' => 'Symbol is required.',
            'symbol.string' => 'Symbol must be text.',
            'symbol.regex' => 'Use 1 to 5 uppercase letters for the symbol.',
            'side.required' => 'Choose buy or sell.',
            'side.in' => 'Side must be buy or sell.',
            'type.required' => 'Choose a limit or market order.',
            'type.in' => 'Order type must be limit or market.',
            'quantity.required' => 'Quantity is required.',
            'quantity.integer' => 'Quantity must be a whole number.',
            'quantity.min' => 'Quantity must be at least 1.',
            'quantity.max' => 'Quantity must not exceed 1,000,000.',
            'price.required_if' => 'Price is required for limit orders.',
            'price.numeric' => 'Price must be a number.',
            'price.gt' => 'Price must be greater than zero.',
            'price.decimal' => 'Price must have at most 4 decimal places.',
            'price.max' => 'Price must not exceed 99,999,999.9999.',
        ];
    }
}
BROKERAGE_REFERENCE_EOF

mkdir -p 'app/Services'
cat > 'app/Services/OrderService.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

namespace App\Services;

use App\Exceptions\ExchangeException;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Throwable;

class OrderService
{
    public function __construct(private readonly ExchangeClient $exchange)
    {
    }

    public function place(array $attributes): Order
    {
        $order = DB::transaction(fn (): Order => Order::create([
            ...$attributes,
            'client_order_id' => (string) Str::uuid(),
            'status' => 'pending',
        ]));

        // The HTTP call must happen outside a database transaction.
        try {
            $response = $this->exchange->submitOrder([
                ...$attributes,
                'client_order_id' => $order->client_order_id,
            ]);
            $result = ['status' => 'accepted', 'exchange_order_id' => $response['exchange_order_id']];
        } catch (ExchangeException $exception) {
            $result = $exception->httpStatus === 422
                ? ['status' => 'rejected', 'rejection_message' => $exception->getMessage()]
                : ['status' => 'unknown'];
            $this->saveResult($order, $result);
            if ($exception->httpStatus === 503) {
                throw new ExchangeException('Order status is unconfirmed. Do not submit it again; contact the broker.', 503);
            }
            throw $exception;
        }

        return $this->saveResult($order, $result);
    }

    private function saveResult(Order $order, array $result): Order
    {
        try {
            return DB::transaction(function () use ($order, $result): Order {
                $order->update($result);
                return $order;
            });
        } catch (Throwable $exception) {
            Log::error('Could not save order result', [
                'order_id' => $order->id,
                'client_order_id' => $order->client_order_id,
            ]);
            throw $exception;
        }
    }
}
BROKERAGE_REFERENCE_EOF

mkdir -p 'app/Http/Controllers'
cat > 'app/Http/Controllers/MarketController.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Services\ExchangeClient;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;

class MarketController extends Controller
{
    public function index(): View
    {
        return view('market', ['demo' => config('services.exchange.demo')]);
    }

    public function data(ExchangeClient $exchange): JsonResponse
    {
        return response()->json($exchange->marketData());
    }
}
BROKERAGE_REFERENCE_EOF

mkdir -p 'app/Http/Controllers'
cat > 'app/Http/Controllers/OrderController.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\StoreOrderRequest;
use App\Services\OrderService;
use Illuminate\Http\JsonResponse;

class OrderController extends Controller
{
    public function store(StoreOrderRequest $request, OrderService $orders): JsonResponse
    {
        $order = $orders->place($request->validated());

        return response()->json([
            'message' => 'Order accepted.',
            'exchange_order_id' => $order->exchange_order_id,
        ], 201);
    }
}
BROKERAGE_REFERENCE_EOF

mkdir -p 'routes'
cat > 'routes/web.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

use App\Http\Controllers\MarketController;
use App\Http\Controllers\OrderController;
use Illuminate\Support\Facades\Route;

Route::get('/', [MarketController::class, 'index']);
Route::get('/market-data', [MarketController::class, 'data'])->middleware('throttle:60,1,market-');
Route::post('/orders', [OrderController::class, 'store'])->middleware('throttle:10,1,orders-');
BROKERAGE_REFERENCE_EOF

mkdir -p 'bootstrap'
cat > 'bootstrap/app.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

use App\Exceptions\ExchangeException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (ExchangeException $exception, Request $request): JsonResponse {
            return response()->json(['message' => $exception->getMessage()], $exception->httpStatus);
        });
        $exceptions->render(function (Throwable $exception, Request $request): ?JsonResponse {
            if ($request->expectsJson()
                && !$exception instanceof ExchangeException
                && !$exception instanceof ValidationException
                && !$exception instanceof HttpExceptionInterface) {
                return response()->json(['message' => 'An unexpected error occurred. Please contact the broker before submitting again.'], 500);
            }
            return null;
        });
    })->create();
BROKERAGE_REFERENCE_EOF

mkdir -p 'resources/data'
cat > 'resources/data/market.json' <<'BROKERAGE_REFERENCE_EOF'
{
  "data": [
    {
      "symbol": "AAPL",
      "last_price": 189.42,
      "bid": 189.4,
      "ask": 189.45,
      "volume": 1204500,
      "change_percent": 0.84,
      "updated_at": "2025-01-15T14:30:05Z",
      "bids": [
        {
          "price": 189.4,
          "quantity": 300
        },
        {
          "price": 189.35,
          "quantity": 400
        },
        {
          "price": 189.3,
          "quantity": 500
        }
      ],
      "asks": [
        {
          "price": 189.45,
          "quantity": 250
        },
        {
          "price": 189.5,
          "quantity": 350
        },
        {
          "price": 189.55,
          "quantity": 450
        }
      ]
    },
    {
      "symbol": "MSFT",
      "last_price": 415.2,
      "bid": 415.18,
      "ask": 415.23,
      "volume": 1204500,
      "change_percent": 0.84,
      "updated_at": "2025-01-15T14:30:05Z",
      "bids": [
        {
          "price": 415.18,
          "quantity": 300
        },
        {
          "price": 415.13,
          "quantity": 400
        },
        {
          "price": 415.08,
          "quantity": 500
        }
      ],
      "asks": [
        {
          "price": 415.23,
          "quantity": 250
        },
        {
          "price": 415.28,
          "quantity": 350
        },
        {
          "price": 415.33,
          "quantity": 450
        }
      ]
    },
    {
      "symbol": "GOOGL",
      "last_price": 175.3,
      "bid": 175.28,
      "ask": 175.33,
      "volume": 1204500,
      "change_percent": 0.84,
      "updated_at": "2025-01-15T14:30:05Z",
      "bids": [
        {
          "price": 175.28,
          "quantity": 300
        },
        {
          "price": 175.23,
          "quantity": 400
        },
        {
          "price": 175.18,
          "quantity": 500
        }
      ],
      "asks": [
        {
          "price": 175.33,
          "quantity": 250
        },
        {
          "price": 175.38,
          "quantity": 350
        },
        {
          "price": 175.43,
          "quantity": 450
        }
      ]
    }
  ]
}
BROKERAGE_REFERENCE_EOF

mkdir -p 'resources/views'
cat > 'resources/views/market.blade.php' <<'BROKERAGE_REFERENCE_EOF'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Brokerage Market</title>
    <style>
        * { box-sizing: border-box; }
        body { margin: 0; background: #f3f5f7; color: #213547; font: 15px/1.5 system-ui, sans-serif; }
        main { max-width: 1200px; margin: auto; padding: 24px; }
        h1 { margin-bottom: 4px; }
        h2 { margin-top: 0; font-size: 20px; }
        h3 { font-size: 16px; }
        .muted { color: #5c6e7e; }
        .layout { display: grid; grid-template-columns: minmax(0, 2fr) minmax(280px, 1fr); gap: 20px; }
        section { background: white; border: 1px solid #dce3e8; padding: 20px; border-radius: 8px; margin-bottom: 20px; }
        .scroll { overflow-x: auto; }
        table { border-collapse: collapse; width: 100%; white-space: nowrap; }
        td, th { padding: 10px; text-align: right; border-bottom: 1px solid #e5eaee; font-size: 13px; }
        th { color: #5c6e7e; }
        th:first-child, td:first-child { text-align: left; }
        button, input, select { font: inherit; padding: 9px; border: 1px solid #bac8d2; border-radius: 4px; }
        button { cursor: pointer; background: #eef3f6; color: #213547; }
        button:disabled { opacity: .6; cursor: wait; }
        button:focus-visible, input:focus-visible, select:focus-visible { outline: 2px solid #227aa7; outline-offset: 2px; }
        .symbol { border: 0; background: none; padding: 0; color: #176087; font-weight: 700; }
        .selected { background: #edf6fb; }
        .depth { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        label { display: block; margin: 12px 0; font-weight: 600; }
        input, select { display: block; width: 100%; margin-top: 4px; background: white; }
        input:disabled { background: #edf0f3; }
        .primary { width: 100%; background: #176087; color: white; border: 0; margin-top: 12px; }
        .field-error, .negative, .error { color: #ab293b; }
        .field-error { display: block; font-size: 12px; font-weight: 400; }
        .positive, .success { color: #14734c; }
        .warning { color: #875a08; }
        .notice { padding: 12px; background: #eef3f6; border-radius: 4px; }
        .demo { background: #fff3d6; padding: 10px 14px; border-radius: 4px; }
        @media (max-width: 800px) { .layout { grid-template-columns: 1fr; } main { padding: 16px; } }
    </style>
</head>
<body>
<main>
    <h1>Brokerage Market</h1>
    <p class="muted">Market data, order-book visibility and order submission.</p>
    @if ($demo)
        <p class="demo">Practice mode: fixed sample prices and depth. Valid orders receive simulated acceptance.</p>
    @endif

    <div class="layout">
        <div>
            <section>
                <h2>Market feed</h2>
                <p id="market-status" role="status" class="muted">Loading market data…</p>
                <button id="refresh" type="button">Refresh</button>
                <div class="scroll">
                    <table>
                        <thead><tr><th>Symbol</th><th>Last</th><th>Bid</th><th>Ask</th><th>Change</th><th>Volume</th><th>Updated</th></tr></thead>
                        <tbody id="market-rows"></tbody>
                    </table>
                </div>
            </section>
            <section>
                <h2 id="book-heading">Order book</h2>
                <p id="book-status" class="muted">Select a symbol in the market feed.</p>
                <div class="depth">
                    <div><h3>Bids</h3><table><thead><tr><th>Price</th><th>Quantity</th></tr></thead><tbody id="bids"></tbody></table></div>
                    <div><h3>Asks</h3><table><thead><tr><th>Price</th><th>Quantity</th></tr></thead><tbody id="asks"></tbody></table></div>
                </div>
            </section>
        </div>
        <section>
            <h2>Place an order</h2>
            <p id="order-status" role="status" hidden></p>
            <form id="order-form">
                <label>Symbol
                    <input name="symbol" required pattern="[A-Z]{1,5}" maxlength="5" placeholder="AAPL" title="Use 1 to 5 uppercase letters.">
                    <span class="field-error" data-error="symbol"></span>
                </label>
                <label>Side
                    <select name="side"><option value="buy">Buy</option><option value="sell">Sell</option></select>
                    <span class="field-error" data-error="side"></span>
                </label>
                <label>Order type
                    <select name="type"><option value="limit">Limit</option><option value="market">Market</option></select>
                    <span class="field-error" data-error="type"></span>
                </label>
                <label>Quantity
                    <input name="quantity" type="number" required min="1" max="1000000" step="1" value="100">
                    <span class="field-error" data-error="quantity"></span>
                </label>
                <label>Limit price
                    <input name="price" type="number" required min="0.0001" max="99999999.9999" step="0.0001">
                    <span class="field-error" data-error="price"></span>
                </label>
                <button id="submit-order" class="primary" type="submit">Submit order</button>
            </form>
            <p class="muted">Acceptance confirms receipt, not execution.</p>
        </section>
    </div>
</main>
<script>
    const form = document.getElementById('order-form');
    const fields = form.elements;
    const marketStatus = document.getElementById('market-status');
    const orderStatus = document.getElementById('order-status');
    const submitButton = document.getElementById('submit-order');
    let market = [];
    let selectedSymbol = null;
    let loadingMarket = false;
    let submitting = false;

    async function request(url, options = {}) {
        const response = await fetch(url, {
            ...options,
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            },
        });
        let body;
        try {
            body = await response.json();
        } catch {
            throw new Error('Could not read the server response.');
        }
        if (!response.ok) {
            const error = new Error(body.message || 'The request failed.');
            error.status = response.status;
            error.errors = body.errors || {};
            throw error;
        }
        return body;
    }

    const price = value => Number(value).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 4 });

    function addCell(row, value, className = '') {
        const cell = row.insertCell();
        cell.textContent = value;
        cell.className = className;
        return cell;
    }

    function renderMarket() {
        const tbody = document.getElementById('market-rows');
        tbody.replaceChildren();
        market.forEach(quote => {
            const row = tbody.insertRow();
            row.className = quote.symbol === selectedSymbol ? 'selected' : '';
            const button = document.createElement('button');
            button.type = 'button';
            button.className = 'symbol';
            button.textContent = quote.symbol;
            button.addEventListener('click', () => {
                selectedSymbol = quote.symbol;
                fields.symbol.value = quote.symbol;
                renderMarket();
                renderBook();
            });
            row.insertCell().append(button);
            ['last_price', 'bid', 'ask'].forEach(key => addCell(row, price(quote[key])));
            addCell(row, `${Number(quote.change_percent).toFixed(2)}%`, quote.change_percent >= 0 ? 'positive' : 'negative');
            addCell(row, Number(quote.volume).toLocaleString());
            addCell(row, new Date(quote.updated_at).toLocaleTimeString());
        });
    }

    function renderBook() {
        const quote = market.find(item => item.symbol === selectedSymbol);
        document.getElementById('book-heading').textContent = `Order book${quote ? ' · ' + quote.symbol : ''}`;
        const hasDepth = Array.isArray(quote?.bids) && Array.isArray(quote?.asks);
        document.getElementById('book-status').textContent = hasDepth
            ? 'Depth supplied with the selected market quote.'
            : 'The market-data response does not include order-book depth.';
        ['bids', 'asks'].forEach(side => {
            const tbody = document.getElementById(side);
            tbody.replaceChildren();
            if (!hasDepth) return;
            quote[side].forEach(level => {
                const row = tbody.insertRow();
                addCell(row, price(level.price));
                addCell(row, Number(level.quantity).toLocaleString());
            });
        });
    }

    async function loadMarket() {
        if (loadingMarket) return;
        loadingMarket = true;
        try {
            const result = await request('/market-data');
            market = result.data;
            if (!market.some(quote => quote.symbol === selectedSymbol)) {
                selectedSymbol = market[0]?.symbol || null;
                if (!fields.symbol.value) fields.symbol.value = selectedSymbol || '';
            }
            renderMarket();
            renderBook();
            marketStatus.className = 'muted';
            marketStatus.textContent = market.length ? 'Refreshes every 3 seconds while this tab is visible.' : 'No market data is available.';
        } catch (error) {
            marketStatus.className = 'error';
            marketStatus.textContent = market.length
                ? 'Could not refresh. Displayed data may be delayed. Use Refresh to retry.'
                : 'Could not load market data. Use Refresh to retry.';
        } finally {
            loadingMarket = false;
        }
    }

    fields.type.addEventListener('change', () => {
        const isMarket = fields.type.value === 'market';
        fields.price.disabled = isMarket;
        fields.price.required = !isMarket;
        if (isMarket) fields.price.value = '';
        document.querySelector('[data-error="price"]').textContent = '';
    });

    form.addEventListener('submit', async event => {
        event.preventDefault();
        if (submitting) return;
        submitting = true;
        submitButton.disabled = true;
        submitButton.textContent = 'Submitting…';
        document.querySelectorAll('[data-error]').forEach(element => element.textContent = '');
        orderStatus.hidden = true;
        try {
            const payload = Object.fromEntries(new FormData(form));
            const result = await request('/orders', { method: 'POST', body: JSON.stringify(payload) });
            orderStatus.className = 'notice success';
            orderStatus.textContent = `Order accepted · ${result.exchange_order_id}`;
        } catch (error) {
            orderStatus.className = error.status === 503 ? 'notice warning' : 'notice error';
            orderStatus.textContent = error.status
                ? error.message
                : 'Could not confirm the order result. Contact the broker before submitting again.';
            document.querySelectorAll('[data-error]').forEach(element => {
                element.textContent = (error.errors?.[element.dataset.error] || []).join(' ');
            });
        } finally {
            orderStatus.hidden = false;
            submitting = false;
            submitButton.disabled = false;
            submitButton.textContent = 'Submit order';
        }
    });

    document.getElementById('refresh').addEventListener('click', loadMarket);
    document.addEventListener('visibilitychange', () => { if (!document.hidden) loadMarket(); });
    setInterval(() => { if (!document.hidden) loadMarket(); }, 3000);
    loadMarket();
</script>
</body>
</html>
BROKERAGE_REFERENCE_EOF

mkdir -p 'tests'
cat > 'tests/TestCase.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
}
BROKERAGE_REFERENCE_EOF

mkdir -p 'tests/Feature'
cat > 'tests/Feature/BrokerageTest.php' <<'BROKERAGE_REFERENCE_EOF'
<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Models\Order;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Tests\TestCase;

class BrokerageTest extends TestCase
{
    use DatabaseMigrations;

    protected function setUp(): void
    {
        parent::setUp();
        Http::preventStrayRequests();
        config(['services.exchange.base_url' => 'https://exchange.test', 'services.exchange.api_key' => 'test-key']);
    }

    private function payload(): array
    {
        return ['symbol' => 'AAPL', 'side' => 'buy', 'type' => 'limit', 'quantity' => 100, 'price' => 189.4];
    }

    public function test_page_and_market_feed(): void
    {
        $market = ['data' => [['symbol' => 'AAPL', 'last_price' => 189.42]]];
        Http::fake(['exchange.test/v1/market-data' => Http::response($market)]);
        $this->get('/')->assertOk()->assertSee('Brokerage Market')->assertSee('csrf-token');
        $this->getJson('/market-data')->assertOk()->assertExactJson($market);
        Http::assertSent(fn ($request): bool => $request->hasHeader('Authorization', 'Bearer test-key'));
    }

    public function test_validation_messages(): void
    {
        $this->postJson('/orders', ['symbol' => 'aapl', 'side' => 'invalid', 'type' => 'limit', 'quantity' => 0])
            ->assertUnprocessable()
            ->assertJsonPath('errors.symbol.0', 'Use 1 to 5 uppercase letters for the symbol.')
            ->assertJsonPath('errors.side.0', 'Side must be buy or sell.')
            ->assertJsonPath('errors.quantity.0', 'Quantity must be at least 1.')
            ->assertJsonPath('errors.price.0', 'Price is required for limit orders.');
        $this->assertDatabaseCount('orders', 0);
        Http::assertNothingSent();
    }

    public function test_order_acceptance_calls_http_outside_transaction(): void
    {
        Http::fake(function ($request) {
            $this->assertSame(0, DB::transactionLevel());
            $this->assertDatabaseHas('orders', ['status' => 'pending', 'client_order_id' => $request['client_order_id']]);
            return Http::response(['exchange_order_id' => 'EX-123', 'status' => 'accepted'], 201);
        });
        $this->postJson('/orders', $this->payload())->assertCreated()->assertJsonPath('exchange_order_id', 'EX-123');
        $this->assertDatabaseHas('orders', ['status' => 'accepted', 'exchange_order_id' => 'EX-123']);
        Http::assertSentCount(1);
    }

    public function test_exchange_rejection_is_persisted(): void
    {
        Http::fake(['*' => Http::response(['error' => ['message' => 'Private upstream detail']], 422)]);
        $this->postJson('/orders', $this->payload())->assertUnprocessable()
            ->assertJsonPath('message', 'The exchange rejected the order. Please check your order details.');
        $this->assertDatabaseHas('orders', ['status' => 'rejected']);
    }

    public function test_timeout_is_unknown_and_not_retried(): void
    {
        Http::fake(['*' => Http::failedConnection()]);
        $this->postJson('/orders', $this->payload())->assertStatus(503)
            ->assertJsonPath('message', 'Order status is unconfirmed. Do not submit it again; contact the broker.');
        $this->assertDatabaseCount('orders', 1);
        $this->assertDatabaseHas('orders', ['status' => 'unknown']);
        $this->assertDatabaseMissing('orders', ['status' => 'rejected']);
        Http::assertSentCount(1);
    }

    public function test_server_error_is_unknown(): void
    {
        Http::fake(['*' => Http::response([], 500)]);
        $this->postJson('/orders', $this->payload())->assertStatus(503);
        $this->assertDatabaseHas('orders', ['status' => 'unknown']);
        Http::assertSentCount(1);
    }

    public function test_market_order_excludes_price(): void
    {
        Http::fake(function ($request) {
            $this->assertArrayNotHasKey('price', $request->data());
            return Http::response(['exchange_order_id' => 'EX-MARKET', 'status' => 'accepted'], 201);
        });
        $this->postJson('/orders', [...$this->payload(), 'type' => 'market'])->assertCreated();
        $this->assertDatabaseHas('orders', ['type' => 'market', 'price' => null]);
    }

    public function test_initial_transaction_failure_leaves_no_order(): void
    {
        Order::created(function (): void {
            throw new RuntimeException('Private database detail');
        });
        try {
            $this->postJson('/orders', $this->payload())->assertStatus(500)
                ->assertJsonPath('message', 'An unexpected error occurred. Please contact the broker before submitting again.');
            $this->assertDatabaseCount('orders', 0);
            Http::assertNothingSent();
        } finally {
            Order::flushEventListeners();
        }
    }

    public function test_final_transaction_failure_leaves_order_pending(): void
    {
        Http::fake(['*' => Http::response(['exchange_order_id' => 'EX-123', 'status' => 'accepted'], 201)]);
        Order::updated(function (): void {
            throw new RuntimeException('Private database detail');
        });
        try {
            $this->postJson('/orders', $this->payload())->assertStatus(500)
                ->assertJsonPath('message', 'An unexpected error occurred. Please contact the broker before submitting again.');
            $this->assertDatabaseHas('orders', ['status' => 'pending', 'exchange_order_id' => null]);
        } finally {
            Order::flushEventListeners();
        }
    }

    public function test_market_polling_does_not_use_the_order_rate_limit(): void
    {
        config(['services.exchange.demo' => true]);
        for ($i = 0; $i < 11; $i++) {
            $this->getJson('/market-data')->assertOk();
        }
        $this->postJson('/orders', $this->payload())->assertCreated();
    }

    public function test_demo_runs_without_exchange_access(): void
    {
        config(['services.exchange.demo' => true]);
        $this->get('/')->assertOk()->assertSee('Practice mode');
        $this->getJson('/market-data')->assertOk()->assertJsonPath('data.0.symbol', 'AAPL');
        $this->postJson('/orders', $this->payload())->assertCreated();
        $this->assertDatabaseHas('orders', ['status' => 'accepted']);
        Http::assertNothingSent();
    }
}
BROKERAGE_REFERENCE_EOF

mkdir -p '.'
cat > 'phpunit.xml' <<'BROKERAGE_REFERENCE_EOF'
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true"
         cacheResult="false"
>
    <testsuites>
        <testsuite name="Feature">
            <directory>tests/Feature</directory>
        </testsuite>
    </testsuites>
    <source>
        <include>
            <directory>app</directory>
        </include>
    </source>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="EXCHANGE_DEMO" value="false" force="true"/>
        <env name="APP_MAINTENANCE_DRIVER" value="file"/>
        <env name="CACHE_STORE" value="array" force="true"/>
        <env name="DB_CONNECTION" value="sqlite" force="true"/>
        <env name="DB_DATABASE" value=":memory:" force="true"/>
        <env name="SESSION_DRIVER" value="array" force="true"/>
    </php>
</phpunit>
BROKERAGE_REFERENCE_EOF

1. .env.example

Copy to .env only for a fresh project. Keep an existing APP_KEY and database settings. This contains no credentials.

APP_NAME="Brokerage Market"
APP_ENV=local
APP_KEY=
APP_DEBUG=false
APP_URL=http://localhost:8000

LOG_CHANNEL=single
DB_CONNECTION=sqlite
SESSION_DRIVER=file
CACHE_STORE=file

EXCHANGE_DEMO=true
EXCHANGE_BASE_URL=
EXCHANGE_API_KEY=

2. config/services.php

On a fresh skeleton replace this file. In a supplied project merge only the exchange key, preserving existing services.

<?php

declare(strict_types=1);

return [
    'exchange' => [
        'base_url' => env('EXCHANGE_BASE_URL', ''),
        'api_key' => env('EXCHANGE_API_KEY', ''),
        'demo' => (bool) env('EXCHANGE_DEMO', true),
    ],
];

3. database/migrations/2026_01_01_000000_create_orders_table.php

Use this migration OR the generated orders migration, never both. DECIMAL(12,4) is enforced by MySQL; SQLite does not enforce decimal precision.

<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class () extends Migration {
    public function up(): void
    {
        Schema::create('orders', function (Blueprint $table): void {
            $table->id();
            $table->uuid('client_order_id')->unique();
            $table->string('exchange_order_id')->nullable()->unique();
            $table->string('symbol');
            $table->string('side');
            $table->string('type');
            $table->unsignedInteger('quantity');
            $table->decimal('price', 12, 4)->nullable();
            $table->string('status')->default('pending');
            $table->text('rejection_message')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('orders');
    }
};

4. app/Models/Order.php

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $fillable = [
        'client_order_id', 'exchange_order_id', 'symbol', 'side', 'type',
        'quantity', 'price', 'status', 'rejection_message',
    ];

    protected function casts(): array
    {
        return ['quantity' => 'integer', 'price' => 'decimal:4'];
    }
}

5. app/Exceptions/ExchangeException.php

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

<?php

declare(strict_types=1);

namespace App\Exceptions;

use RuntimeException;

class ExchangeException extends RuntimeException
{
    public function __construct(string $message, public readonly int $httpStatus)
    {
        parent::__construct($message);
    }
}

6. app/Services/ExchangeClient.php

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

<?php

declare(strict_types=1);

namespace App\Services;

use App\Exceptions\ExchangeException;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class ExchangeClient
{
    public function marketData(): array
    {
        if (config('services.exchange.demo')) {
            return json_decode(file_get_contents(resource_path('data/market.json')), true, flags: JSON_THROW_ON_ERROR);
        }

        return $this->request('GET', '/v1/market-data');
    }

    public function submitOrder(array $payload): array
    {
        if (config('services.exchange.demo')) {
            return [
                'exchange_order_id' => 'DEMO-'.$payload['client_order_id'],
                'client_order_id' => $payload['client_order_id'],
                'status' => 'accepted',
            ];
        }

        return $this->request('POST', '/v1/orders', $payload);
    }

    private function request(string $method, string $path, array $payload = []): array
    {
        try {
            $response = Http::withToken(config('services.exchange.api_key'))
                ->baseUrl(config('services.exchange.base_url'))
                ->acceptJson()
                ->asJson()
                ->timeout(5)
                ->connectTimeout(2)
                ->send($method, $path, $method === 'POST' ? ['json' => $payload] : []);
        } catch (ConnectionException $exception) {
            Log::warning('Exchange connection failed', ['path' => $path]);
            throw new ExchangeException('The exchange is temporarily unavailable.', 503);
        }

        if (!$response->successful()) {
            Log::warning('Exchange request failed', ['path' => $path, 'status' => $response->status()]);
            if ($method === 'POST' && $response->clientError()) {
                throw new ExchangeException('The exchange rejected the order. Please check your order details.', 422);
            }
            throw new ExchangeException('The exchange is temporarily unavailable.', 503);
        }

        $data = $response->json();
        $valid = is_array($data) && ($method === 'GET'
            ? isset($data['data']) && is_array($data['data'])
            : is_string($data['exchange_order_id'] ?? null) && ($data['status'] ?? null) === 'accepted');
        if (!$valid) {
            Log::warning('Exchange returned an unexpected response', ['path' => $path]);
            throw new ExchangeException('The exchange returned an unexpected response.', 503);
        }

        return $data;
    }
}

7. app/Http/Requests/StoreOrderRequest.php

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

<?php

declare(strict_types=1);

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreOrderRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'symbol' => ['required', 'string', 'regex:/^[A-Z]{1,5}$/'],
            'side' => ['required', 'in:buy,sell'],
            'type' => ['required', 'in:limit,market'],
            'quantity' => ['required', 'integer', 'min:1', 'max:1000000'],
            'price' => ['exclude_if:type,market', 'required_if:type,limit', 'nullable', 'numeric', 'gt:0', 'decimal:0,4', 'max:99999999.9999'],
        ];
    }

    public function messages(): array
    {
        return [
            'symbol.required' => 'Symbol is required.',
            'symbol.string' => 'Symbol must be text.',
            'symbol.regex' => 'Use 1 to 5 uppercase letters for the symbol.',
            'side.required' => 'Choose buy or sell.',
            'side.in' => 'Side must be buy or sell.',
            'type.required' => 'Choose a limit or market order.',
            'type.in' => 'Order type must be limit or market.',
            'quantity.required' => 'Quantity is required.',
            'quantity.integer' => 'Quantity must be a whole number.',
            'quantity.min' => 'Quantity must be at least 1.',
            'quantity.max' => 'Quantity must not exceed 1,000,000.',
            'price.required_if' => 'Price is required for limit orders.',
            'price.numeric' => 'Price must be a number.',
            'price.gt' => 'Price must be greater than zero.',
            'price.decimal' => 'Price must have at most 4 decimal places.',
            'price.max' => 'Price must not exceed 99,999,999.9999.',
        ];
    }
}

8. app/Services/OrderService.php

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

<?php

declare(strict_types=1);

namespace App\Services;

use App\Exceptions\ExchangeException;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Throwable;

class OrderService
{
    public function __construct(private readonly ExchangeClient $exchange)
    {
    }

    public function place(array $attributes): Order
    {
        $order = DB::transaction(fn (): Order => Order::create([
            ...$attributes,
            'client_order_id' => (string) Str::uuid(),
            'status' => 'pending',
        ]));

        // The HTTP call must happen outside a database transaction.
        try {
            $response = $this->exchange->submitOrder([
                ...$attributes,
                'client_order_id' => $order->client_order_id,
            ]);
            $result = ['status' => 'accepted', 'exchange_order_id' => $response['exchange_order_id']];
        } catch (ExchangeException $exception) {
            $result = $exception->httpStatus === 422
                ? ['status' => 'rejected', 'rejection_message' => $exception->getMessage()]
                : ['status' => 'unknown'];
            $this->saveResult($order, $result);
            if ($exception->httpStatus === 503) {
                throw new ExchangeException('Order status is unconfirmed. Do not submit it again; contact the broker.', 503);
            }
            throw $exception;
        }

        return $this->saveResult($order, $result);
    }

    private function saveResult(Order $order, array $result): Order
    {
        try {
            return DB::transaction(function () use ($order, $result): Order {
                $order->update($result);
                return $order;
            });
        } catch (Throwable $exception) {
            Log::error('Could not save order result', [
                'order_id' => $order->id,
                'client_order_id' => $order->client_order_id,
            ]);
            throw $exception;
        }
    }
}

9. app/Http/Controllers/MarketController.php

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Services\ExchangeClient;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;

class MarketController extends Controller
{
    public function index(): View
    {
        return view('market', ['demo' => config('services.exchange.demo')]);
    }

    public function data(ExchangeClient $exchange): JsonResponse
    {
        return response()->json($exchange->marketData());
    }
}

10. app/Http/Controllers/OrderController.php

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\StoreOrderRequest;
use App\Services\OrderService;
use Illuminate\Http\JsonResponse;

class OrderController extends Controller
{
    public function store(StoreOrderRequest $request, OrderService $orders): JsonResponse
    {
        $order = $orders->place($request->validated());

        return response()->json([
            'message' => 'Order accepted.',
            'exchange_order_id' => $order->exchange_order_id,
        ], 201);
    }
}

11. routes/web.php

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

<?php

declare(strict_types=1);

use App\Http\Controllers\MarketController;
use App\Http\Controllers\OrderController;
use Illuminate\Support\Facades\Route;

Route::get('/', [MarketController::class, 'index']);
Route::get('/market-data', [MarketController::class, 'data'])->middleware('throttle:60,1,market-');
Route::post('/orders', [OrderController::class, 'store'])->middleware('throttle:10,1,orders-');

12. bootstrap/app.php

Fresh Laravel 11/12 skeleton: replace. In an existing app merge the exception handlers and preserve routing, middleware and providers.

<?php

declare(strict_types=1);

use App\Exceptions\ExchangeException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (ExchangeException $exception, Request $request): JsonResponse {
            return response()->json(['message' => $exception->getMessage()], $exception->httpStatus);
        });
        $exceptions->render(function (Throwable $exception, Request $request): ?JsonResponse {
            if ($request->expectsJson()
                && !$exception instanceof ExchangeException
                && !$exception instanceof ValidationException
                && !$exception instanceof HttpExceptionInterface) {
                return response()->json(['message' => 'An unexpected error occurred. Please contact the broker before submitting again.'], 500);
            }
            return null;
        });
    })->create();

13. resources/data/market.json

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

{
  "data": [
    {
      "symbol": "AAPL",
      "last_price": 189.42,
      "bid": 189.4,
      "ask": 189.45,
      "volume": 1204500,
      "change_percent": 0.84,
      "updated_at": "2025-01-15T14:30:05Z",
      "bids": [
        {
          "price": 189.4,
          "quantity": 300
        },
        {
          "price": 189.35,
          "quantity": 400
        },
        {
          "price": 189.3,
          "quantity": 500
        }
      ],
      "asks": [
        {
          "price": 189.45,
          "quantity": 250
        },
        {
          "price": 189.5,
          "quantity": 350
        },
        {
          "price": 189.55,
          "quantity": 450
        }
      ]
    },
    {
      "symbol": "MSFT",
      "last_price": 415.2,
      "bid": 415.18,
      "ask": 415.23,
      "volume": 1204500,
      "change_percent": 0.84,
      "updated_at": "2025-01-15T14:30:05Z",
      "bids": [
        {
          "price": 415.18,
          "quantity": 300
        },
        {
          "price": 415.13,
          "quantity": 400
        },
        {
          "price": 415.08,
          "quantity": 500
        }
      ],
      "asks": [
        {
          "price": 415.23,
          "quantity": 250
        },
        {
          "price": 415.28,
          "quantity": 350
        },
        {
          "price": 415.33,
          "quantity": 450
        }
      ]
    },
    {
      "symbol": "GOOGL",
      "last_price": 175.3,
      "bid": 175.28,
      "ask": 175.33,
      "volume": 1204500,
      "change_percent": 0.84,
      "updated_at": "2025-01-15T14:30:05Z",
      "bids": [
        {
          "price": 175.28,
          "quantity": 300
        },
        {
          "price": 175.23,
          "quantity": 400
        },
        {
          "price": 175.18,
          "quantity": 500
        }
      ],
      "asks": [
        {
          "price": 175.33,
          "quantity": 250
        },
        {
          "price": 175.38,
          "quantity": 350
        },
        {
          "price": 175.43,
          "quantity": 450
        }
      ]
    }
  ]
}

14. resources/views/market.blade.php

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Brokerage Market</title>
    <style>
        * { box-sizing: border-box; }
        body { margin: 0; background: #f3f5f7; color: #213547; font: 15px/1.5 system-ui, sans-serif; }
        main { max-width: 1200px; margin: auto; padding: 24px; }
        h1 { margin-bottom: 4px; }
        h2 { margin-top: 0; font-size: 20px; }
        h3 { font-size: 16px; }
        .muted { color: #5c6e7e; }
        .layout { display: grid; grid-template-columns: minmax(0, 2fr) minmax(280px, 1fr); gap: 20px; }
        section { background: white; border: 1px solid #dce3e8; padding: 20px; border-radius: 8px; margin-bottom: 20px; }
        .scroll { overflow-x: auto; }
        table { border-collapse: collapse; width: 100%; white-space: nowrap; }
        td, th { padding: 10px; text-align: right; border-bottom: 1px solid #e5eaee; font-size: 13px; }
        th { color: #5c6e7e; }
        th:first-child, td:first-child { text-align: left; }
        button, input, select { font: inherit; padding: 9px; border: 1px solid #bac8d2; border-radius: 4px; }
        button { cursor: pointer; background: #eef3f6; color: #213547; }
        button:disabled { opacity: .6; cursor: wait; }
        button:focus-visible, input:focus-visible, select:focus-visible { outline: 2px solid #227aa7; outline-offset: 2px; }
        .symbol { border: 0; background: none; padding: 0; color: #176087; font-weight: 700; }
        .selected { background: #edf6fb; }
        .depth { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        label { display: block; margin: 12px 0; font-weight: 600; }
        input, select { display: block; width: 100%; margin-top: 4px; background: white; }
        input:disabled { background: #edf0f3; }
        .primary { width: 100%; background: #176087; color: white; border: 0; margin-top: 12px; }
        .field-error, .negative, .error { color: #ab293b; }
        .field-error { display: block; font-size: 12px; font-weight: 400; }
        .positive, .success { color: #14734c; }
        .warning { color: #875a08; }
        .notice { padding: 12px; background: #eef3f6; border-radius: 4px; }
        .demo { background: #fff3d6; padding: 10px 14px; border-radius: 4px; }
        @media (max-width: 800px) { .layout { grid-template-columns: 1fr; } main { padding: 16px; } }
    </style>
</head>
<body>
<main>
    <h1>Brokerage Market</h1>
    <p class="muted">Market data, order-book visibility and order submission.</p>
    @if ($demo)
        <p class="demo">Practice mode: fixed sample prices and depth. Valid orders receive simulated acceptance.</p>
    @endif

    <div class="layout">
        <div>
            <section>
                <h2>Market feed</h2>
                <p id="market-status" role="status" class="muted">Loading market data…</p>
                <button id="refresh" type="button">Refresh</button>
                <div class="scroll">
                    <table>
                        <thead><tr><th>Symbol</th><th>Last</th><th>Bid</th><th>Ask</th><th>Change</th><th>Volume</th><th>Updated</th></tr></thead>
                        <tbody id="market-rows"></tbody>
                    </table>
                </div>
            </section>
            <section>
                <h2 id="book-heading">Order book</h2>
                <p id="book-status" class="muted">Select a symbol in the market feed.</p>
                <div class="depth">
                    <div><h3>Bids</h3><table><thead><tr><th>Price</th><th>Quantity</th></tr></thead><tbody id="bids"></tbody></table></div>
                    <div><h3>Asks</h3><table><thead><tr><th>Price</th><th>Quantity</th></tr></thead><tbody id="asks"></tbody></table></div>
                </div>
            </section>
        </div>
        <section>
            <h2>Place an order</h2>
            <p id="order-status" role="status" hidden></p>
            <form id="order-form">
                <label>Symbol
                    <input name="symbol" required pattern="[A-Z]{1,5}" maxlength="5" placeholder="AAPL" title="Use 1 to 5 uppercase letters.">
                    <span class="field-error" data-error="symbol"></span>
                </label>
                <label>Side
                    <select name="side"><option value="buy">Buy</option><option value="sell">Sell</option></select>
                    <span class="field-error" data-error="side"></span>
                </label>
                <label>Order type
                    <select name="type"><option value="limit">Limit</option><option value="market">Market</option></select>
                    <span class="field-error" data-error="type"></span>
                </label>
                <label>Quantity
                    <input name="quantity" type="number" required min="1" max="1000000" step="1" value="100">
                    <span class="field-error" data-error="quantity"></span>
                </label>
                <label>Limit price
                    <input name="price" type="number" required min="0.0001" max="99999999.9999" step="0.0001">
                    <span class="field-error" data-error="price"></span>
                </label>
                <button id="submit-order" class="primary" type="submit">Submit order</button>
            </form>
            <p class="muted">Acceptance confirms receipt, not execution.</p>
        </section>
    </div>
</main>
<script>
    const form = document.getElementById('order-form');
    const fields = form.elements;
    const marketStatus = document.getElementById('market-status');
    const orderStatus = document.getElementById('order-status');
    const submitButton = document.getElementById('submit-order');
    let market = [];
    let selectedSymbol = null;
    let loadingMarket = false;
    let submitting = false;

    async function request(url, options = {}) {
        const response = await fetch(url, {
            ...options,
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            },
        });
        let body;
        try {
            body = await response.json();
        } catch {
            throw new Error('Could not read the server response.');
        }
        if (!response.ok) {
            const error = new Error(body.message || 'The request failed.');
            error.status = response.status;
            error.errors = body.errors || {};
            throw error;
        }
        return body;
    }

    const price = value => Number(value).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 4 });

    function addCell(row, value, className = '') {
        const cell = row.insertCell();
        cell.textContent = value;
        cell.className = className;
        return cell;
    }

    function renderMarket() {
        const tbody = document.getElementById('market-rows');
        tbody.replaceChildren();
        market.forEach(quote => {
            const row = tbody.insertRow();
            row.className = quote.symbol === selectedSymbol ? 'selected' : '';
            const button = document.createElement('button');
            button.type = 'button';
            button.className = 'symbol';
            button.textContent = quote.symbol;
            button.addEventListener('click', () => {
                selectedSymbol = quote.symbol;
                fields.symbol.value = quote.symbol;
                renderMarket();
                renderBook();
            });
            row.insertCell().append(button);
            ['last_price', 'bid', 'ask'].forEach(key => addCell(row, price(quote[key])));
            addCell(row, `${Number(quote.change_percent).toFixed(2)}%`, quote.change_percent >= 0 ? 'positive' : 'negative');
            addCell(row, Number(quote.volume).toLocaleString());
            addCell(row, new Date(quote.updated_at).toLocaleTimeString());
        });
    }

    function renderBook() {
        const quote = market.find(item => item.symbol === selectedSymbol);
        document.getElementById('book-heading').textContent = `Order book${quote ? ' · ' + quote.symbol : ''}`;
        const hasDepth = Array.isArray(quote?.bids) && Array.isArray(quote?.asks);
        document.getElementById('book-status').textContent = hasDepth
            ? 'Depth supplied with the selected market quote.'
            : 'The market-data response does not include order-book depth.';
        ['bids', 'asks'].forEach(side => {
            const tbody = document.getElementById(side);
            tbody.replaceChildren();
            if (!hasDepth) return;
            quote[side].forEach(level => {
                const row = tbody.insertRow();
                addCell(row, price(level.price));
                addCell(row, Number(level.quantity).toLocaleString());
            });
        });
    }

    async function loadMarket() {
        if (loadingMarket) return;
        loadingMarket = true;
        try {
            const result = await request('/market-data');
            market = result.data;
            if (!market.some(quote => quote.symbol === selectedSymbol)) {
                selectedSymbol = market[0]?.symbol || null;
                if (!fields.symbol.value) fields.symbol.value = selectedSymbol || '';
            }
            renderMarket();
            renderBook();
            marketStatus.className = 'muted';
            marketStatus.textContent = market.length ? 'Refreshes every 3 seconds while this tab is visible.' : 'No market data is available.';
        } catch (error) {
            marketStatus.className = 'error';
            marketStatus.textContent = market.length
                ? 'Could not refresh. Displayed data may be delayed. Use Refresh to retry.'
                : 'Could not load market data. Use Refresh to retry.';
        } finally {
            loadingMarket = false;
        }
    }

    fields.type.addEventListener('change', () => {
        const isMarket = fields.type.value === 'market';
        fields.price.disabled = isMarket;
        fields.price.required = !isMarket;
        if (isMarket) fields.price.value = '';
        document.querySelector('[data-error="price"]').textContent = '';
    });

    form.addEventListener('submit', async event => {
        event.preventDefault();
        if (submitting) return;
        submitting = true;
        submitButton.disabled = true;
        submitButton.textContent = 'Submitting…';
        document.querySelectorAll('[data-error]').forEach(element => element.textContent = '');
        orderStatus.hidden = true;
        try {
            const payload = Object.fromEntries(new FormData(form));
            const result = await request('/orders', { method: 'POST', body: JSON.stringify(payload) });
            orderStatus.className = 'notice success';
            orderStatus.textContent = `Order accepted · ${result.exchange_order_id}`;
        } catch (error) {
            orderStatus.className = error.status === 503 ? 'notice warning' : 'notice error';
            orderStatus.textContent = error.status
                ? error.message
                : 'Could not confirm the order result. Contact the broker before submitting again.';
            document.querySelectorAll('[data-error]').forEach(element => {
                element.textContent = (error.errors?.[element.dataset.error] || []).join(' ');
            });
        } finally {
            orderStatus.hidden = false;
            submitting = false;
            submitButton.disabled = false;
            submitButton.textContent = 'Submit order';
        }
    });

    document.getElementById('refresh').addEventListener('click', loadMarket);
    document.addEventListener('visibilitychange', () => { if (!document.hidden) loadMarket(); });
    setInterval(() => { if (!document.hidden) loadMarket(); }, 3000);
    loadMarket();
</script>
</body>
</html>

15. tests/TestCase.php

Fresh skeleton only; preserve existing test setup in supplied projects.

<?php

declare(strict_types=1);

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
}

16. tests/Feature/BrokerageTest.php

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Models\Order;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Tests\TestCase;

class BrokerageTest extends TestCase
{
    use DatabaseMigrations;

    protected function setUp(): void
    {
        parent::setUp();
        Http::preventStrayRequests();
        config(['services.exchange.base_url' => 'https://exchange.test', 'services.exchange.api_key' => 'test-key']);
    }

    private function payload(): array
    {
        return ['symbol' => 'AAPL', 'side' => 'buy', 'type' => 'limit', 'quantity' => 100, 'price' => 189.4];
    }

    public function test_page_and_market_feed(): void
    {
        $market = ['data' => [['symbol' => 'AAPL', 'last_price' => 189.42]]];
        Http::fake(['exchange.test/v1/market-data' => Http::response($market)]);
        $this->get('/')->assertOk()->assertSee('Brokerage Market')->assertSee('csrf-token');
        $this->getJson('/market-data')->assertOk()->assertExactJson($market);
        Http::assertSent(fn ($request): bool => $request->hasHeader('Authorization', 'Bearer test-key'));
    }

    public function test_validation_messages(): void
    {
        $this->postJson('/orders', ['symbol' => 'aapl', 'side' => 'invalid', 'type' => 'limit', 'quantity' => 0])
            ->assertUnprocessable()
            ->assertJsonPath('errors.symbol.0', 'Use 1 to 5 uppercase letters for the symbol.')
            ->assertJsonPath('errors.side.0', 'Side must be buy or sell.')
            ->assertJsonPath('errors.quantity.0', 'Quantity must be at least 1.')
            ->assertJsonPath('errors.price.0', 'Price is required for limit orders.');
        $this->assertDatabaseCount('orders', 0);
        Http::assertNothingSent();
    }

    public function test_order_acceptance_calls_http_outside_transaction(): void
    {
        Http::fake(function ($request) {
            $this->assertSame(0, DB::transactionLevel());
            $this->assertDatabaseHas('orders', ['status' => 'pending', 'client_order_id' => $request['client_order_id']]);
            return Http::response(['exchange_order_id' => 'EX-123', 'status' => 'accepted'], 201);
        });
        $this->postJson('/orders', $this->payload())->assertCreated()->assertJsonPath('exchange_order_id', 'EX-123');
        $this->assertDatabaseHas('orders', ['status' => 'accepted', 'exchange_order_id' => 'EX-123']);
        Http::assertSentCount(1);
    }

    public function test_exchange_rejection_is_persisted(): void
    {
        Http::fake(['*' => Http::response(['error' => ['message' => 'Private upstream detail']], 422)]);
        $this->postJson('/orders', $this->payload())->assertUnprocessable()
            ->assertJsonPath('message', 'The exchange rejected the order. Please check your order details.');
        $this->assertDatabaseHas('orders', ['status' => 'rejected']);
    }

    public function test_timeout_is_unknown_and_not_retried(): void
    {
        Http::fake(['*' => Http::failedConnection()]);
        $this->postJson('/orders', $this->payload())->assertStatus(503)
            ->assertJsonPath('message', 'Order status is unconfirmed. Do not submit it again; contact the broker.');
        $this->assertDatabaseCount('orders', 1);
        $this->assertDatabaseHas('orders', ['status' => 'unknown']);
        $this->assertDatabaseMissing('orders', ['status' => 'rejected']);
        Http::assertSentCount(1);
    }

    public function test_server_error_is_unknown(): void
    {
        Http::fake(['*' => Http::response([], 500)]);
        $this->postJson('/orders', $this->payload())->assertStatus(503);
        $this->assertDatabaseHas('orders', ['status' => 'unknown']);
        Http::assertSentCount(1);
    }

    public function test_market_order_excludes_price(): void
    {
        Http::fake(function ($request) {
            $this->assertArrayNotHasKey('price', $request->data());
            return Http::response(['exchange_order_id' => 'EX-MARKET', 'status' => 'accepted'], 201);
        });
        $this->postJson('/orders', [...$this->payload(), 'type' => 'market'])->assertCreated();
        $this->assertDatabaseHas('orders', ['type' => 'market', 'price' => null]);
    }

    public function test_initial_transaction_failure_leaves_no_order(): void
    {
        Order::created(function (): void {
            throw new RuntimeException('Private database detail');
        });
        try {
            $this->postJson('/orders', $this->payload())->assertStatus(500)
                ->assertJsonPath('message', 'An unexpected error occurred. Please contact the broker before submitting again.');
            $this->assertDatabaseCount('orders', 0);
            Http::assertNothingSent();
        } finally {
            Order::flushEventListeners();
        }
    }

    public function test_final_transaction_failure_leaves_order_pending(): void
    {
        Http::fake(['*' => Http::response(['exchange_order_id' => 'EX-123', 'status' => 'accepted'], 201)]);
        Order::updated(function (): void {
            throw new RuntimeException('Private database detail');
        });
        try {
            $this->postJson('/orders', $this->payload())->assertStatus(500)
                ->assertJsonPath('message', 'An unexpected error occurred. Please contact the broker before submitting again.');
            $this->assertDatabaseHas('orders', ['status' => 'pending', 'exchange_order_id' => null]);
        } finally {
            Order::flushEventListeners();
        }
    }

    public function test_market_polling_does_not_use_the_order_rate_limit(): void
    {
        config(['services.exchange.demo' => true]);
        for ($i = 0; $i < 11; $i++) {
            $this->getJson('/market-data')->assertOk();
        }
        $this->postJson('/orders', $this->payload())->assertCreated();
    }

    public function test_demo_runs_without_exchange_access(): void
    {
        config(['services.exchange.demo' => true]);
        $this->get('/')->assertOk()->assertSee('Practice mode');
        $this->getJson('/market-data')->assertOk()->assertJsonPath('data.0.symbol', 'AAPL');
        $this->postJson('/orders', $this->payload())->assertCreated();
        $this->assertDatabaseHas('orders', ['status' => 'accepted']);
        Http::assertNothingSent();
    }
}

17. phpunit.xml

Uses isolated in-memory SQLite, never the application database. Preserve additional test suites in supplied projects.

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true"
         cacheResult="false"
>
    <testsuites>
        <testsuite name="Feature">
            <directory>tests/Feature</directory>
        </testsuite>
    </testsuites>
    <source>
        <include>
            <directory>app</directory>
        </include>
    </source>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="EXCHANGE_DEMO" value="false" force="true"/>
        <env name="APP_MAINTENANCE_DRIVER" value="file"/>
        <env name="CACHE_STORE" value="array" force="true"/>
        <env name="DB_CONNECTION" value="sqlite" force="true"/>
        <env name="DB_DATABASE" value=":memory:" force="true"/>
        <env name="SESSION_DRIVER" value="array" force="true"/>
    </php>
</phpunit>

Return to setup: configure, migrate, test, serve →