Databricks Apps for Governed Dark-Pool Oversight and Institutional AI Workflows
Speaker background
The speaker moved from in-house entertainment and media production into freelance application development for proprietary trading firms and small and medium-sized businesses using institutional-grade AI.
Entertainment production and application development share a practical discipline. Both turn specialist work into an experience that other people can use. A data scientist can create a strong model, but the model produces little business value if a customer, trader, line manager, compliance officer, or operations analyst cannot use it safely through an understandable interface.
This guide creates a Databricks App for dark-pool oversight. The application does not operate a dark pool, route an order, reveal hidden liquidity, or help a user exploit non-public order information. It provides a governed control surface for customers, traders, proprietary-firm line managers, compliance, surveillance, operations, risk, and audit stakeholders.
The application supports controlled data access, participant inquiries, trading-quality review, venue analysis, alert triage, exception annotation, evidence preservation, and human-approved case management.
Important dark-pool boundary
A dark pool is generally an alternative trading system that does not publish its order book before execution. Dark pools are commonly used by institutional investors seeking to execute large orders with less public market impact. Executed trades remain subject to the applicable reporting framework.
The prototype must not expose another participant's unexecuted order, confidential trading intent, subscriber identity, hidden order size, proprietary matching logic, or information that could facilitate front-running, spoofing, wash trading, market manipulation, discriminatory access, or misuse of material non-public information.
For a United States NMS Stock ATS, Regulation ATS and Form ATS-N obligations can apply. The operating broker-dealer must maintain written safeguards and procedures protecting subscribers' confidential trading information. FINRA publishes delayed OTC activity reported by ATSs and member firms, but this delayed transparency data is not a live execution feed.
A firm operating in Hong Kong, Singapore, the European Union, the United Kingdom, or another jurisdiction must map the application to the relevant licensing, market-structure, transaction-reporting, best-execution, surveillance, recordkeeping, privacy, outsourcing, and cybersecurity requirements. This guide is a technical prototype and not a legal determination that a firm may operate an ATS, crossing network, systematic internaliser, or other non-displayed venue.
Databricks Free Edition boundary
Databricks Free Edition is a perpetual, no-cost, serverless-only cloud environment for learning and prototyping. It provides no production service-level agreement and is governed by fair-use limits.
Free Edition supports up to three Databricks Apps per account. An app runs for up to 24 hours after it is started, updated, or redeployed, and then stops automatically. It can be restarted. Free Edition also includes one SQL warehouse limited to 2X-Small, one AI Search endpoint limited to one search unit, and restricted model-serving capabilities.
Use synthetic participants, accounts, parent orders, child orders, executions, market data, inquiries, alerts, policies, and annotations. Do not upload live subscriber orders, customer identities, production credentials, confidential venue logic, client allocations, real surveillance cases, or restricted market data.
The Free Edition prototype demonstrates application behavior and governance. It must not sit in the path of a production order, cancellation, execution, kill switch, trade report, allocation, or settlement instruction.
Why Databricks Apps
Traditional data applications often export data to an external database, deploy a separate web server, configure containers or virtual machines, establish network routes, implement authentication, manage load balancing, and duplicate permissions in another platform.
Databricks Apps runs containerized applications on Databricks serverless infrastructure. Each app has an isolated runtime, a unique URL, and a dedicated service principal. Applications can use Databricks SQL, Unity Catalog, AI Search, Lakebase, Model Serving, and other approved platform resources.
Databricks handles application hosting and platform authentication. Developers still need to design authorization, validate inputs, protect secrets, manage dependencies, monitor logs, review generated code, and control every write operation.
Supported application patterns include Streamlit, Dash, Gradio, Flask, FastAPI, and Node.js frameworks. This guide uses Streamlit because it supports a rapid controlled prototype with forms, data tables, filters, charts, and session-aware interaction.
The application reads governed Delta data through Databricks SQL and writes only to narrow action, annotation, and case tables. It must not grant the user broad modification rights over raw order or execution records.
Step 1: Define the stakeholder experiences
Create one application with role-aware pages, or separate apps if the security boundaries require stronger isolation.
The customer or subscriber page should provide:
- Submitted inquiry status.
- Executed-trade quality summary.
- Approved venue disclosures.
- Complaint and review submission.
- Evidence references available to that customer.
- No visibility into another subscriber's activity.
The trader page should provide:
- The trader's own parent orders and completed executions.
- Fill rate, execution price, benchmark comparison, venue allocation, and timing summary.
- Open surveillance requests requiring explanation.
- Approved response and annotation forms.
- No access to confidential counterparty identity or other desks' hidden orders.
The proprietary-firm line-manager page should provide:
- Desk-level order and execution summaries.
- Concentration, information-leakage indicators, excessive re-routing, abnormal cancellation, and venue-quality alerts.
- Human approval workflow for reducing access, pausing a strategy, or escalating a case.
- No direct order-entry or cancellation control in the Free Edition app.
The compliance and surveillance page should provide:
- Alert triage.
- Potential wash-trading, spoofing, information-leakage, restricted-list, and best-execution indicators.
- Evidence lineage and case history.
- Escalation and disposition forms.
The operations page should provide:
- Trade-reporting exceptions.
- Missing execution identifiers.
- Allocation and booking breaks.
- Duplicate and late reports.
- Reconciliation status.
The audit page should provide read-only access to approved evidence, lineage, action history, model version, application version, and policy version.
Step 2: Create the Databricks Free Edition workspace
Create a Free Edition workspace named:
dark_pool_control_apps_free_nonprod
Create these workspace folders:
00_environment01_synthetic_data02_governance03_surveillance_features04_ai_search05_model_serving06_app_source07_evaluation08_audit
Create a notebook named 00_environment_check and run:
SELECT current_user() AS current_user, current_catalog() AS current_catalog, current_schema() AS current_schema, current_timestamp() AS checked_at; Record that the environment is synthetic, non-production, serverless-only, quota-limited, and disconnected from all execution venues.
Step 3: Create the Unity Catalog data model
Create the catalog and schemas:
CREATE CATALOG IF NOT EXISTS dark_pool_lab; CREATE SCHEMA IF NOT EXISTS dark_pool_lab.raw; CREATE SCHEMA IF NOT EXISTS dark_pool_lab.silver; CREATE SCHEMA IF NOT EXISTS dark_pool_lab.gold; CREATE SCHEMA IF NOT EXISTS dark_pool_lab.reference; CREATE SCHEMA IF NOT EXISTS dark_pool_lab.actions; CREATE SCHEMA IF NOT EXISTS dark_pool_lab.knowledge; CREATE SCHEMA IF NOT EXISTS dark_pool_lab.governance; If catalog creation is restricted, create the schemas in the default catalog.
Create an approved participant table:
CREATE TABLE IF NOT EXISTS dark_pool_lab.reference.participants ( participant_id STRING, participant_name STRING, participant_type STRING, jurisdiction STRING, customer_segment STRING, onboarding_status STRING, permitted_products ARRAY<STRING>, permitted_venues ARRAY<STRING>, effective_from TIMESTAMP, effective_to TIMESTAMP, is_synthetic BOOLEAN ) USING DELTA; Create an account-to-desk map:
CREATE TABLE IF NOT EXISTS dark_pool_lab.reference.accounts ( account_id STRING, participant_id STRING, firm_id STRING, desk_id STRING, trader_id STRING, strategy_id STRING, jurisdiction STRING, approved BOOLEAN, effective_from TIMESTAMP, effective_to TIMESTAMP, is_synthetic BOOLEAN ) USING DELTA; Step 4: Create synthetic order and execution tables
Create parent orders:
CREATE TABLE IF NOT EXISTS dark_pool_lab.raw.parent_orders ( parent_order_id STRING, account_id STRING, trader_id STRING, created_at TIMESTAMP, instrument_id STRING, side STRING, order_quantity DECIMAL(24,8), limit_price DECIMAL(24,10), benchmark_type STRING, strategy_type STRING, restricted_flag BOOLEAN, is_synthetic BOOLEAN, ingested_at TIMESTAMP ) USING DELTA; Create venue-routed child orders:
CREATE TABLE IF NOT EXISTS dark_pool_lab.raw.child_orders ( child_order_id STRING, parent_order_id STRING, submitted_at TIMESTAMP, venue_id STRING, routing_algorithm STRING, side STRING, quantity DECIMAL(24,8), limit_price DECIMAL(24,10), minimum_quantity DECIMAL(24,8), time_in_force STRING, order_status STRING, cancelled_at TIMESTAMP, is_synthetic BOOLEAN, ingested_at TIMESTAMP ) USING DELTA; Create executions:
CREATE TABLE IF NOT EXISTS dark_pool_lab.raw.executions ( execution_id STRING, child_order_id STRING, parent_order_id STRING, execution_time TIMESTAMP, venue_id STRING, instrument_id STRING, side STRING, executed_quantity DECIMAL(24,8), executed_price DECIMAL(24,10), reference_bid DECIMAL(24,10), reference_ask DECIMAL(24,10), reference_mid DECIMAL(24,10), reporting_status STRING, is_synthetic BOOLEAN, ingested_at TIMESTAMP ) USING DELTA; Do not store an opposing subscriber identity in the application-facing execution table. Where regulatory or control processing requires counterparty details, keep them in a separately restricted schema.
Step 5: Create case and annotation tables
Create a surveillance-alert table:
CREATE TABLE IF NOT EXISTS dark_pool_lab.gold.surveillance_alerts ( alert_id STRING, detected_at TIMESTAMP, alert_type STRING, severity STRING, participant_id STRING, account_id STRING, trader_id STRING, instrument_id STRING, parent_order_id STRING, measured_value DECIMAL(24,8), threshold_value DECIMAL(24,8), evidence_reference STRING, model_version STRING, alert_status STRING, is_synthetic BOOLEAN ) USING DELTA; Create an append-only case event ledger:
CREATE TABLE IF NOT EXISTS dark_pool_lab.actions.case_events ( event_id STRING, case_id STRING, alert_id STRING, event_time TIMESTAMP, actor_identity STRING, actor_role STRING, action_type STRING, action_reason STRING, previous_state STRING, requested_state STRING, evidence_reference STRING, application_version STRING, is_synthetic BOOLEAN, recorded_at TIMESTAMP ) USING DELTA; Create correction requests rather than allowing users to overwrite source records:
CREATE TABLE IF NOT EXISTS dark_pool_lab.actions.data_correction_requests ( request_id STRING, source_table STRING, source_record_id STRING, requested_by STRING, requested_at TIMESTAMP, issue_type STRING, proposed_value STRING, reason STRING, evidence_reference STRING, approval_status STRING, approved_by STRING, approved_at TIMESTAMP, is_synthetic BOOLEAN ) USING DELTA; The app should append a correction request. A controlled pipeline validates and applies an approved correction to a curated table. It must not change the immutable raw event.
Step 6: Generate a safe synthetic dataset
Generate at least:
- 20 synthetic participants.
- 100 accounts.
- 50 traders.
- 10,000 parent orders.
- 30,000 child orders.
- 15,000 executions.
- 500 surveillance alerts.
- 100 policy documents.
Include normal and abnormal scenarios:
- Large institutional parent order split across venues.
- Low fill rate.
- Price improvement at midpoint.
- Repeated rapid cancellations.
- Excessive reuse of one venue.
- Execution after apparent information leakage.
- Potential self-match across commonly controlled accounts.
- Late trade report.
- Duplicate execution record.
- Trader explanation and compliance disposition.
Mark every record with is_synthetic = true.
Do not create a simulation that predicts or reveals a hidden counterparty's current order. Use historical synthetic events to test controls.
Step 7: Create execution-quality metrics
Create a curated execution-quality view:
CREATE OR REPLACE VIEW dark_pool_lab.gold.execution_quality AS SELECT e.execution_id, e.parent_order_id, e.execution_time, e.venue_id, e.instrument_id, e.side, e.executed_quantity, e.executed_price, e.reference_mid, CASE WHEN e.side = 'BUY' THEN (e.reference_mid - e.executed_price) / NULLIF(e.reference_mid, 0) * 10000 WHEN e.side = 'SELL' THEN (e.executed_price - e.reference_mid) / NULLIF(e.reference_mid, 0) * 10000 END AS midpoint_improvement_bps, e.reporting_status, e.is_synthetic FROM dark_pool_lab.raw.executions e; Create parent-order fill metrics:
CREATE OR REPLACE VIEW dark_pool_lab.gold.parent_order_summary AS SELECT p.parent_order_id, p.account_id, p.trader_id, p.instrument_id, p.side, p.order_quantity, COALESCE(SUM(e.executed_quantity), 0) AS executed_quantity, COALESCE(SUM(e.executed_quantity), 0) / NULLIF(p.order_quantity, 0) AS fill_rate, SUM(e.executed_quantity * e.executed_price) / NULLIF(SUM(e.executed_quantity), 0) AS execution_vwap, COUNT(DISTINCT e.venue_id) AS executing_venue_count, p.is_synthetic FROM dark_pool_lab.raw.parent_orders p LEFT JOIN dark_pool_lab.raw.executions e ON p.parent_order_id = e.parent_order_id GROUP BY p.parent_order_id, p.account_id, p.trader_id, p.instrument_id, p.side, p.order_quantity, p.is_synthetic; Do not present midpoint improvement as complete best-execution evidence. Also review opportunity cost, adverse selection, fill probability, latency, market impact, fees, information leakage, routing alternatives, and order instructions.
Step 8: Define surveillance indicators
Use surveillance indicators to prioritize human review, not to make automatic misconduct findings.
Potential self-match or wash-trading indicator:
- Common beneficial owner or firm control.
- Opposite-side trading in the same or economically equivalent instrument.
- Close execution times.
- Small net risk change.
- Repeated pattern.
Potential spoofing indicator:
- Large non-bona-fide orders.
- High cancellation rate.
- Orders placed and cancelled around opposite-side fills.
- Repeated market influence pattern.
Potential information-leakage indicator:
- Material unfavorable price movement after routing to a venue.
- Repeated venue-specific adverse movement.
- Execution quality deterioration by order size or strategy.
- Short time between routing and suspicious external activity.
Potential venue-control indicator:
- Unapproved participant category.
- Inconsistent access treatment.
- Execution outside approved price or matching rules.
- Missing report.
- Confidential-data access outside authorized operations.
Every alert must retain input timestamps, feature values, thresholds, model or rule version, and evidence lineage.
Step 9: Apply Unity Catalog security
Create groups:
dark_pool_customersdark_pool_tradersprop_firm_line_managersmarket_surveillancetrade_operationscompliance_officersindependent_auditapp_developers
Grant the app access only to required views and action tables.
Use user authorization for pages requiring individual row-level access. Databricks Apps supports OAuth-based user authorization so the application can act with the interacting user's identity and permissions.
Use app authorization for shared background work such as loading approved configuration or writing application telemetry. Every app receives a dedicated service principal. Its permissions must be granted explicitly.
Do not rely on app authorization alone when different users must see different data. Under app authorization, users share the app service principal's permissions.
Apply row filters that restrict participants to their records, traders to their own activity, and line managers to their desks.
Apply column masks to customer names, account identifiers, employee identities, and restricted surveillance fields where users need only tokenized identifiers.
Treat the app's permission and the user's permission as two independent boundaries. Grant neither broad catalog ownership nor unrestricted MODIFY access.
Step 10: Create stakeholder-safe views
Create a customer view that excludes confidential venue and subscriber details:
CREATE OR REPLACE VIEW dark_pool_lab.gold.customer_execution_view AS SELECT p.parent_order_id, p.account_id, p.instrument_id, p.side, p.order_quantity, s.executed_quantity, s.fill_rate, s.execution_vwap, s.executing_venue_count, p.created_at, p.is_synthetic FROM dark_pool_lab.raw.parent_orders p JOIN dark_pool_lab.gold.parent_order_summary s ON p.parent_order_id = s.parent_order_id; Create a trader view containing only the trader's own orders and alerts.
Create a line-manager view aggregated by desk, strategy, venue, and risk classification.
Create a compliance view with detailed evidence references but keep legal-privilege and investigation notes in a separately restricted table.
Create an audit view containing immutable event history, model version, app version, source lineage, and approval references.
Step 11: Create the Databricks App
Open Apps and select Create App.
Name the app:
dark-pool-control-center
Choose the Streamlit template.
Copy the app's dedicated service-principal identity from the Authorization page.
Grant the app service principal:
-
CAN USEon the Free Edition SQL warehouse. -
USE CATALOGondark_pool_lab. -
USE SCHEMAon required schemas. -
SELECTon approved views. -
MODIFYonly oncase_eventsanddata_correction_requestsif app authorization is used for controlled writes.
Do not grant MODIFY on raw orders, executions, participants, accounts, alerts, or policies.
Step 12: Create the application files
Create requirements.txt:
streamlit pandas databricks-sdk databricks-sql-connector Create app.yaml:
command: - streamlit - run - app.py - --server.port - "8000" - --server.address - "0.0.0.0" Store the SQL warehouse resource in the app configuration. Do not ask business users to type a warehouse HTTP path or table name.
Use environment variables supplied through the app resource configuration rather than hard-coded identifiers.
Step 13: Build the application connection layer
Create app.py with app-scoped authentication:
import os import uuid import pandas as pd import streamlit as st from databricks import sql from databricks.sdk.core import Config cfg = Config() def get_connection(): host = cfg.host.replace("https://", "").replace("http://", "") return sql.connect( server_hostname=host, http_path=os.environ["DATABRICKS_WAREHOUSE_HTTP_PATH"], credentials_provider=lambda: cfg.authenticate, _use_arrow_native_complex_types=False, ) def run_query(statement, parameters=None): with get_connection() as connection: with connection.cursor() as cursor: cursor.execute(statement, parameters or []) if cursor.description: return cursor.fetchall_arrow().to_pandas() return pd.DataFrame() Use parameterized queries. Never concatenate a user-provided table name, identity, date expression, status, or free text directly into SQL.
Use an allowlist for page names, sort columns, filter columns, and case actions.
Step 14: Build the role-aware navigation
Read the authenticated user context through the supported Databricks Apps user-authorization pattern.
Map the user's group membership to approved pages.
Show only pages authorized for the identity:
- Customer Summary.
- Trader Review.
- Line Manager Control.
- Surveillance Triage.
- Operations Exceptions.
- Compliance Case.
- Audit Evidence.
Do not hide a page only in the browser. Every query must remain protected by Unity Catalog permissions, row filters, masks, and user authorization.
When the identity cannot be resolved or there is no authorized role, deny access and record the denied event without exposing data.
Step 15: Build the customer page
Allow an authorized customer to filter by date, in...