A high-performance, real-time trading terminal simulator built entirely with client-side web technologies.
[Play Now] | [Documentation] | [Report Bug] | [Request Feature]
This project provides a highly accurate, tick-by-tick financial market microstructure simulation. Engineered for quantitative analysis, strategy backtesting, and educational purposes, it allows users to interact with synthetic markets featuring authentic liquidity constraints, timezone synchronization, dynamic macroeconomic news, and derivatives pricing models.
📑 Table of Contents (Click to expand)
The application is built with a strict focus on zero-latency execution and high-frequency DOM updates.
graph TD
UI[Frontend UI HTML/CSS] -->|DOM Updates| RenderEngine[Batched Rendering Engine]
RenderEngine --> State[In-Memory State Manager]
State --> Matching[Order Matching Engine]
State --> Market[Market Tick Generator]
Market -->|Correlated Shocks| News[Macro News Engine]
- Frontend Framework: Vanilla HTML5, CSS3, JavaScript (ES5/ES6).
- State Management: 100% in-memory client-side architecture. Order queues, portfolio states, and tick histories are managed in browser memory without reliance on external databases or APIs.
- Rendering Engine: Utilizes batched DOM updates and optimized rendering loops to sustain thousands of tick updates per second without UI degradation.
To ensure the simulation feels authentic to professional quants and traders, the engine relies on rigorous mathematical modeling under the hood:
- Asset Pricing (Stochastic Calculus): Tick generation is modeled using a modified Geometric Brownian Motion (GBM) algorithm. Asset prices drift and diffuse based on their assigned
volatilityMultiplier, meaning highly volatile assets (e.g., Crypto) exhibit wider Gaussian walks than stable assets (e.g., Bonds). - Order Book Liquidity Modeling: Level 2 Order Book depth is not infinite. It is synthetically generated using logarithmic scaling against the asset's predefined Base Volume. Large market orders will suffer from realistic slippage as they eat through the synthetic bids/asks.
- Derivatives Pricing: The options chain utilizes a dynamic pricing model akin to Black-Scholes. Premium decay is calculated daily (Theta), and price elasticity (Delta/Gamma) shifts in real-time as the underlying asset moves in and out of the money.
- Algorithmic Cross-Market Correlation: Assets don't move in a vacuum. A complex Correlation Matrix links global assets. If a major macroeconomic news event shocks the US Tech sector, the engine mathematically computes the ripple effect, instantly applying correlated price impacts to Asian component suppliers, global tech indices, and related cryptocurrencies.
The simulation enforces strict market microstructure rules, rejecting the concept of infinite liquidity found in basic simulators.
- Tick Volume Modeling: Order book depth is mathematically scaled to the real-world daily volume of specific asset classes. Order execution is constrained by available synthetic liquidity.
- Asynchronous Exchange Hours: The engine tracks the operating hours of global exchanges (NYSE, NASDAQ, NSE, TSE, SSE, HKEX, LSE). Assets are only tradable during their respective timezone sessions.
- After-Hours Processing: When an exchange closes, its order book state is frozen. Market orders are rejected, while Limit and Stop orders are securely queued for the subsequent market open.
- Circuit Breakers: Simulates exchange-mandated trading halts. Assets experiencing extreme volatility (±10%) hit Upper or Lower Circuit Limits, instantly drying up order book liquidity and preventing execution.
- Live Aggregation: Global indices (e.g., S&P 500, NIFTY 50, HSI, STOXX 600) are rigorously tied to their underlying constituent stocks.
- Market-Cap Weighting: Index prices update concurrently based on the real-time share prices and shares outstanding of their components.
- Overnight Gaps: When markets open, indices accurately gap up or down based on the overnight pre-market movements of their underlying assets.
A robust routing and execution engine supporting advanced order types and Time-in-Force (TIF) instructions.
- Market & Limit Orders: Executes immediately against available liquidity or guarantees execution at the specified limit price.
- Stop Orders: Triggers upon price crossing a specified threshold, instantly converting to a Market order to capture momentum.
- Time In Force (TIF): Supports DAY, IOC (Immediate or Cancel), and FOK (Fill or Kill) instructions. Partial fills and immediate cancellations are modeled accurately.
- Position Limits: Implements algebraic exposure calculation to enforce strict maximum position caps and prevent exploitation.
- Procedural Sentiment Generation: Over 80+ dynamic macroeconomic events ranging from Central Bank rate hikes to geopolitical conflicts.
- Cross-Market Correlation: Events impacting specific sectors or regions (e.g., Chinese Infrastructure stimulus) will logically ripple through the entire global market, hitting correlated assets (e.g., Copper, Emerging Markets).
- Overnight Shocks: If a global news event occurs while a specific market is closed, the shock is stored and applied as a massive Gap Up / Gap Down the moment the market opens.
- Inline Studio Modal: Access a fully-featured, embedded CodeMirror IDE as a seamless overlay within the terminal without losing market context.
- Algorithmic Strategy Creation: Write raw JavaScript trading algorithms that interact with a secure sandbox exposing historical data, technical indicators, and portfolio state.
- Built-in HFT & Momentum Models: Includes 10 pre-configured strategies ranging from simple Mean Reversions to High-Frequency Volatility Breakouts and Statistical Arbitrage.
- Comprehensive Backtesting: Define Stop-Loss (SL), Take-Profit (TP), and Starting Capital to simulate realistic outcomes over historical tick data.
- Performance Analytics: View detailed backtest results including an interactive Equity Curve chart (powered by Chart.js), Win Rate, Profit Factor, Max Drawdown, and a complete trade-by-trade log.
- Synthetic Options: Supports Call and Put options on underlying equities.
- Live Greeks Calculation: Dynamically computes premium pricing using standard risk metrics (Delta, Gamma, Theta, Vega).
- Time Decay: Options premiums realistically decay as the contract approaches expiry (Theta).
- Clearing & Settlement: Automated End-of-Day (EOD) processing handles the exercise or expiration of derivatives based on the underlying asset's closing price.
- Equities: Instruments from US, Indian, Japanese, Chinese, Hong Kong, and European exchanges.
- Indices: Tracking major benchmarks (S&P 500, NIFTY 50, Nikkei 225, HSI, DAX, FTSE 100).
- Commodities: Futures-style contracts for precious metals and energy.
- Cryptocurrency: Continuous 24/7 trading for digital assets.
- Forex (FX) & Fixed Income: Currency pairs and sovereign debt yields.
- Automated FX Conversion: Real-time cross-currency conversion dynamically settles international P&L into the base portfolio currency.
- Dynamic Credit Scoring: Tracks a live CIBIL Score (300-900) based on financial behavior, affecting loan eligibility and interest rates.
- Margin Loans: Take out short-term, high-interest loans to multiply buying power. Daily EMI is automatically deducted from the cash margin.
- Fixed Deposits: Lock in excess cash for guaranteed risk-free returns over set maturity periods.
- Liquidations & Defaults: Failing to cover daily loan EMIs triggers CIBIL score penalties and forces immediate liquidation of trading assets to cover debts.
- Property Portfolio: Buy, hold, and sell 30 unique global properties spanning Residential, Commercial, and Luxury sectors.
- Dynamic Rent Collection: Earn daily rental yields automatically based on the live fluctuating market value of owned properties.
- Mortgages & Foreclosure: Purchase properties with 20% down payments via 14-day mortgages. Missing EMI payments results in bank foreclosure, asset seizure, and severe credit damage.
- Dynamic UI Theming: Switch between multiple highly polished color palettes including Deep Dark Mode, Cyberpunk, and Light/Sepia Mode.
- Typography Control: Swap between modern sans-serif fonts (Outfit, Inter) and developer-focused monospace fonts (Roboto Mono, JetBrains Mono).
- Live Styling Overrides: The UI instantly reacts and re-renders components using CSS Variables to apply user customization seamlessly.
- Underground Crates: Utilize excess cash to purchase Bronze, Silver, or Gold crates that drop randomized, powerful market perks.
- Insider Advantages: Unlock temporary rule-bending mechanics such as Brokerage Holiday (zero trading fees), Circuit Override (bypass exchange halts), Market Freeze (pause time to evaluate positions), and Profit Amplifier (boosted returns).
- Time Acceleration: Fast-forward the market simulation at 10x Speed to quickly backtest strategies across multiple trading days.
- Market Freeze: Manually pause the simulation engine to calmly review portfolio metrics, analyze charts, and place complex order setups without latency pressure.
- Critical Financial Fixes: Corrected options pricing time-decay (Theta) math to ensure highly accurate Black-Scholes modeling.
- Margin & Liquidity Accuracy: Overhauled short-selling margin logic so collateral is fully and accurately released upon covering.
-
Algorithmic Performance: Rewrote SMA and Bollinger Bands calculations to an efficient
$O(N)$ sliding window, preventing false signals. -
Enhanced Security: Integrated a strict Content-Security-Policy (CSP) and added robust
try/catchexecution for custom bot algorithms. - Bug Squashing: Patched 20+ UI, charting, and accounting bugs including fixing double-counted options margins, correcting loan amortizations, and restoring multi-day historical candlestick data.
The application requires no backend configuration or package installation. It runs entirely locally in your browser.
- Clone the repository to your local environment:
git clone https://github.com/yourusername/tradingterminal.git
- Navigate into the project directory:
cd tradingterminal - Open
index.htmlin any modern web browser (Google Chrome, Firefox, Safari, Edge). - The simulation engine will initialize automatically. No build step is required!
Tip
Use the categorical tabs (Equities, Indices, Crypto) to navigate the asset universe. Select an instrument to render its live chart and Level 2 Market Depth order book.
New to the terminal? The simulation is designed to mirror real-world finance, mixed with gamified progression. Here is how the core loop works:
- The simulation operates on a day-by-day basis, starting at 12:00 AM and running until the end of the day.
- As time ticks forward, markets open and close based on their real-world timezones. For example, Indian stocks are only tradable between 09:15 AM and 03:30 PM.
- Once the day ends, you must manually click Start Next Day to process overnight settlement, decay options time-value (Theta), and deduct loan EMIs.
- Market Orders: Buy/Sell instantly at whatever liquidity is currently available.
- Limit & Stop Orders: Specify exact prices. These wait in your pending order queue until the market reaches your target.
- Spread Matters: You always buy at the Ask (higher price) and sell at the Bid (lower price).
- Need more capital? Visit Dalal Bank to take out a Margin Loan.
- Loans give you immediate buying power but require a daily EMI deducted automatically at the end of each day.
- Keep an eye on your CIBIL Score. Making profits and paying EMIs keeps it high. Missing an EMI drops your score, increases your interest rates, and can trigger forced liquidation (Bankruptcy) where the broker forcibly sells your assets to recover the debt!
- You can trade Call and Put options from the Option Chain. Options give you massive leverage but lose value every day due to time decay.
- Options are cash-settled automatically on their expiry day. Make sure you manage your margin carefully, as Shorting options blocks a significant amount of capital!
- Got spare cash? Buy Crates from the Syndicate to unlock rule-bending perks.
- Use perks like Brokerage Holidays (0% fees), Circuit Overrides (trade halted stocks), or Market Freezes (pause the clock) to gain an unfair edge over the market.
- Use the Export Statement button to generate a beautiful, printable HTML report of your complete trading history, P&L, and portfolio performance to track your growth over time.
The Trading Terminal Simulator was conceived to bridge the gap between theoretical financial knowledge and practical market dynamics without the inherent risk of actual capital loss.
Many basic simulators provide infinite liquidity and instant execution, which fails to prepare users for the realities of slippage, partial fills, and liquidity constraints. This project addresses these shortcomings by implementing a robust, purely client-side matching engine that accurately models order book depth, time-in-force instructions, and realistic market constraints.
Whether you are a student learning market microstructure, a developer studying low-latency JavaScript rendering, or a quant enthusiast testing logic against synthetic ticks, this simulator provides a rich, uncompromising environment.
Contributions, issues, and feature requests are welcome!
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
Warning
This software is a SIMULATOR. All market data, pricing models, and liquidity metrics are generated by mathematical algorithms. It does not reflect live data from actual financial exchanges and is strictly intended for educational, testing, and entertainment purposes. Do not use this software for actual financial trading or decision-making.