# The Terminal (`/dataterminal`)

The terminal is one page: chart (left/top), order form (right), positions/orders (bottom). On phones it swaps into a dedicated mobile layout; the positions area can also be condensed, minimized, or full-screened. Nearly every layout choice, panel positions, chart split, timeframes, toggled overlays, panel heights, is saved locally and restored the next time you open the page.

A demo variant of the same page lives at `/demo-trade`. It shows a **// DEMO** badge instead of **// CONNECTED**, trades against a demo balance and demo positions, and hides live-account-only areas (the **TP/SL** and **Assets** tabs, the account switcher, and the disconnect button).

---

## Symbol selection

- **Symbol button** (chart toolbar, e.g. **BTC** with a chevron, tooltip **Change Symbol**) opens the symbol search modal: type in the **type to search...** field and pick any listed perpetual pair.
- On mobile, tapping the symbol name in the header (e.g. **BTCUSDT**) opens the same search overlay.
- Clicking a symbol in the positions table also switches the chart to that asset.
- The chosen symbol is reflected in the URL (`/dataterminal/<SYMBOL>`), so links are shareable.

## Ticker header

The stats bar above the chart shows, live for the selected pair:

| Field | Content |
|---|---|
| **24H Change** | 24-hour percent change (green/red) |
| **Mark Price** | Live price (streams from the chart feed) |
| **Index Price** | Index price |
| **24H High** / **24H Low** | 24-hour extremes from BloFin ticker data |
| **Funding Rate/Countdown** | Current funding rate (%) and an `HH:MM:SS` countdown to the next funding time |
| **24H Volume** | 24-hour volume, formatted as $K / $M / $B |

Ticker data refreshes every 15 seconds while the tab is visible. The bar can be hidden via **Chart Settings → Ticker Bar**.

---

## Chart

**Data**: candles stream from MEXC with BloFin as automatic fallback; live ticks over WebSocket. First paint happens after **one** page of history (2,000 bars), the rest of the 10,000-bar history backfills in the background with your zoom preserved, and the newest ~1,500 bars per symbol/timeframe are session-cached so reloads paint instantly.

### Timeframes

The single timeframe button (shows the current frame, e.g. **15m**) opens a dropdown:

- **Timeframes** grid: `1m 3m 5m 15m 30m 1h 2h 4h 8h 12h 1d 3d 1w 1M 3M`.
- **Custom** section: enter any minute value from **2 to 120** in the **e.g. 7** input and press Enter or the **+** button. Custom frames are aggregated client-side from 1-minute candles, appear as their own buttons (e.g. **7m**), and can be removed with the small **×** that appears on hover. The custom list persists across sessions.
- Your last timeframe is remembered **per symbol**. Switching to a previously viewed timeframe paints instantly from cache and refreshes only the newest page.

### Chart Settings (gear icon, tooltip **Chart Settings**)

| Toggle | Effect |
|---|---|
| **Heiken Ashi** | Repaints candles as Heikin-Ashi (persisted) |
| **Grid Lines** | Show/hide chart grid |
| **Light Mode** | Light chart theme (also flips the whole terminal's light mode) |
| **Panel Position** | Moves side data panels **LEFT**/**RIGHT** |
| **Ticker Bar** | Show/hide the ticker header |
| **Tutorial** | Starts the guided terminal tutorial |

### Indicators

The **Indicators** button opens the indicator modal (**INDICATORS** header) with a search box (**Search indicators...**) and category tabs: **ALL**, **Overlays**, **Oscillators**, **Trend**, **Volume**, **Volatility**, **CFE**, **Other**, **Custom**. There are **85 built-in indicators**; a footer shows `85 indicators available` and how many are active.

| Category | Examples |
|---|---|
| **Overlays: Moving Averages** | SMA, EMA, WMA, Hull MA, DEMA, TEMA, KAMA, ZLEMA, VWMA, ALMA, SMMA, McGinley |
| **Overlays: Price Averages** | VWAP, LinReg, Typical Price, Median Price |
| **Overlays: Bands & Channels** | Bollinger Bands, Keltner Channel, Donchian Channel, Price Envelope, Regression Channel, Price Channel, Rainbow Deviation |
| **Overlays: Trend Following** | SuperTrend, Parabolic SAR, Ichimoku, Chandelier Exit |
| **Overlays: Valuation** | Mayer Multiple, Coinbase Premium |
| **Oscillators** | RSI, Stoch RSI, Stochastic, Williams %R, CCI, MFI, CMO, Ultimate Osc, Awesome Osc, Fisher Transform, RVI, Laguerre RSI, TSI, %B, Schaff Trend |
| **Trend** | MACD, PPO, ADX, Aroon, Vortex, DMI, Elder Ray, KST, Coppock, Momentum, ROC, TRIX, DPO |
| **Volatility** | ATR, Std Dev, Hist Volatility, HV, Choppiness, Mass Index, TTM Squeeze, BBWP |
| **Volume** | Volume, OBV, CMF, Force Index, Ease of Move, Vol Oscillator, Chaikin Osc, Klinger |
| **Other** | Pivot Points, Fibonacci, Zig Zag |
| **CFE** | CFE Avg Entry, CFE Avg Stop Loss, CFE Avg Take Profit, CFE Liquidation Levels, CFE Overview Report |

**Per-instance settings**: every active indicator appears as a chip in the toolbar (e.g. `RSI (14)`, `MACD (12,26,9)`, `BOLLINGER (20,2)`). Each chip has a gear (**Edit settings**) opening an inline editor with a **Color** picker plus numeric fields matching that indicator, **Period**, **Std Dev**, **Multiplier**, **Fast/Slow/Signal**, **%K Period / %D Period**, **Slowing**, **Percent**, **RSI Period**, **Stoch Period**, **Period 1/2/3**, **Conversion/Base/Lagging 2/Displacement** (Ichimoku), **Deviation**, **Gamma**, **V Factor**, **Offset**, **Sigma**, **Step**, **Max**, **Long/Short ROC**, **WMA**, **Long/Short Period**, **BB Mult**, **Kelt Mult**, **BB Length**, **Lookback**, whichever apply. Press Enter to apply, Escape to close. Chips also carry **Hide**/**Show** and an **×** to remove. Indicator selections persist across symbols and sessions.

**Sub-Charts** (own panel below the price chart, listed in the modal under **Sub-Charts**):

| Panel | Description |
|---|---|
| **Open Interest** | Aggregate OI below chart |
| **Volume Delta** | Buy vs sell volume delta |
| **Volume** | Trading volume in separate pane |
| **RSI (14)** | RSI oscillator in separate pane (editable **Period**) |
| **MACD** | MACD line, signal, histogram (editable **Fast**/**Slow**/**Signal**) |

**Show/Hide toolbar**: the eye button (**Show**/**Hide**) collapses the whole indicator toolbar row.

**Starring**: star icons next to items in the Essentials / Liq Levels / Smart Overlays menus add them to the **Starred Indicators** dropdown (star button with a count) for one-click ON/OFF toggling. If nothing is starred it reads *"No starred indicators yet. Star indicators in the Indicators modal."*

### Essentials dropdown

Quick toggles with a **Toggle All** switch:

- **EMAs**: **EMA 6**, **EMA 12**, **EMA 20**
- **Period opens**: **Weekly Open**, **Monthly Open**, **Yearly Open**
- **Trade overlays**: **LP Levels**, **TP/SL Lines**, **Open Orders**, **PNL Display**, **Entry Price**, **Trade Line**

With **Trade Line** on, your open positions render on the chart as draggable pills showing live P&L; TP/SL lines are drag-to-adjust, and open limit orders can be shown and dragged as well.

### Liq Levels dropdown (tooltip **Liquidation Levels**)

Estimated liquidation clusters, with **Toggle All**:

| Group | Toggles |
|---|---|
| **LTF Liquidations** | **24H Long Liq**, **24H Short Liq**, **3D Long Liq**, **3D Short Liq** |
| **HTF Liquidations** | **7D Long Liq**, **7D Short Liq**, **30D Long Liq**, **30D Short Liq** |

### Smart Overlays dropdown (tooltip **Smart Zones**)

Collapsible categories, each row a star + ON/OFF toggle, plus **Toggle All**:

| Category | Overlays |
|---|---|
| **Structure** | **Supply / Demand**, **Fair Value Gaps**, **Liquidity Sweeps** |
| **Risk Zones** | **No Trade Zone** |
| **Extremes** | **Rainbow Runner**, **Range Deviation** (settings: **Fallback Bars** 10–500), **SMA Dev + RSI** (settings: **SMA Period**, **RSI Period**, **Entry Dev %**, **RSI Overbought**, **RSI Oversold**, **Exit Dev %**), **Rainbow Deviation**, **Trend Deviation** (settings: **MA Period**, **RSI Period**, **Extreme Dev %**, **Slope Weight**, "Colors candles green/red based on MA deviation") |
| **Valuation** | **Mayer Multiple** |
| **MA Overlays** | **Golden / Death Cross**, **EMA Ribbon (8–89)** |

Active smart overlays show as removable chips in the toolbar (**S/D**, **FVG**, **Liq Sweeps**, **NTZ**, **Rainbow**, **Deviation**, **SMA Dev**, **Trend Dev**, **G/D Cross**, **EMA Ribbon**).

Additional overlay groups reachable from the toolbar menus include **CME** lines (**Market Close**, **Market Open**, **CME Display**, CME gap), higher-timeframe **MA50/MA200** for 4H / 1D / 1W, Bitcoin **Halving Display** / **Halving Markers**, **TPO (POC, VAH, VAL)**, and **Multi-TF Momentum**.

### CFE dropdown (tooltip **CFE Counter-Fade Levels**)

**CFE LEVELS**, "Counter-Fade Engine overlays from losing cohort positions". Toggle each CFE indicator individually (**CFE Avg Entry**, **CFE Avg Stop Loss**, "your target TP for the fade", **CFE Avg Take Profit**, "invalidation zone for the fade", **CFE Liquidation Levels**, **CFE Overview Report**) or use **Enable All CFE** / **Disable All CFE**.

### Custom Tools dropdown

Lists your saved custom (AI-built) indicators and PineScript scripts with ON/OFF toggles and delete buttons, plus three entry points:

- **PineScript**: opens the native PineScript editor.
- **Python**: opens the Python Runner.
- **Build with AI**: opens the Indicator Workshop.

#### Indicator Workshop (step by step)

A full-screen editor (**INDICATOR WORKSHOP**) with a live preview chart on the left (own timeframe row: 1m 5m 15m 30m 1h 4h 1d) and a chat panel on the right.

1. Open it via **Custom Tools → Build with AI** (or **Build New** inside the indicator modal's **Custom** tab).
2. Describe the indicator in plain language in **Describe your indicator...**: starter suggestions are offered ("VWAP with 2 standard deviation bands", "RSI with divergence signals", "Supertrend with ATR-based coloring").
3. Generation runs in the background ("Generating indicator...", then "Still generating... (Ns)"; it errors with *"Generation timed out. Please try again."* after ~5 minutes).
4. The draft renders immediately on the preview chart. Use the eye button to show/hide the preview, and the code button (**Toggle code view**) to inspect the generated code, its color, and whether it is an **Overlay** or **Sub-chart**.
5. Keep refining conversationally (*"change period to 20"*): the assistant may offer follow-up **Suggestions** you can click.
6. **Save to Library** stores it to your account (*"…saved to your library. You can enable it from the Custom tab."*). The library button lists saved indicators with **Load & edit** and **Delete**; the restart button starts over.
7. Drafts persist: reopening the workshop restores your work (*"Draft restored. Continue refining or save to library."*).

Pasted PineScript does **not** go through the AI: the **Paste PineScript (native, no AI conversion)** button routes to the native PineScript executor.

#### PineScript editor (native execution)

The **PINESCRIPT** modal ("Native PineScript Execution") has an optional **Indicator Name** field ("Auto-detected from indicator() title...") and a **PineScript Code** area. **Save & Run** (or **Update Script** when editing) compiles and runs it in your browser and adds it to Custom Tools. Errors show inline in red. Supported per the in-modal note: `ta.sma, ta.ema, ta.rsi, ta.macd, ta.atr, ta.stoch, ta.stdev, ta.wma, ta.vwma, ta.highest, ta.lowest, ta.crossover, ta.crossunder, ta.change, ta.rma`, math functions, `input()`, `plot()`, `hline()`, `var/varip`, for loops, if/else, ternaries, and series indexing with `[]`.

#### Python Runner

The **PYTHON RUNNER** modal ("Run Python against chart candles") gives your script a `candles` list of dicts (`time, open, high, low, close, volume`); `print()` output appears in an **Output** pane. Runs sandboxed in the browser via Pyodide (first run loads the runtime, "~10s").

### Drawing tools

A vertical toolbar on the left edge of the chart (desktop only):

| Tool | Notes |
|---|---|
| **Pointer (Esc)** | Select/move/edit drawings |
| **Ray** | Two-point trendline |
| **Extended Line** | Extends both directions |
| **Horizontal** | One click, full-width level |
| **Vertical** | One click, vertical line |
| **Arrow** | Two-point arrow |
| **Ruler** | Measure price/time between two points |
| **Rectangle** | Two-corner box |
| **Channel** | Parallel channel |
| **Freehand** | Draw freely |
| **Fibonacci** | Retracement with levels 0 / 0.236 / 0.382 / 0.5 / 0.618 / 0.786 / 1 |
| **Text** | Click, type a label (Escape cancels) |
| **Long R:R** | Long risk/reward box (entry, TP above, SL below; draggable handles) |
| **Short R:R** | Short risk/reward box |

Below the tools: line style buttons (**solid**, **dashed**, **dotted**), a **Color** picker, **Delete Selected (Del)** when a drawing is selected, and **Clear All**. Drawings are saved to your account per symbol and shared across all timeframes; the AI chat draws through the same pipeline.

### Chart split

The split control offers **1 / 2 / 3 / 4** charts: 2 and 3 split side-by-side, 4 is a 2×2 grid. Each extra chart gets its own symbol picker (searchable dropdown) and timeframe, defaulting to 15m / 1h / 4h / 1d across charts 1–4. Split mode, per-chart symbols, and per-chart timeframes are all persisted.

### Scale controls and P&L widgets

On the chart itself: an **Auto Scale** button re-fits the price axis and a **Logarithmic Scale** button toggles log pricing. With **PNL Display** enabled, a draggable P&L readout (tooltip **Drag to reposition**) floats over the chart summarizing open-position profit, with an inline **Close position** shortcut and a **Hide P&L display** control; its position is remembered.

### Side data panels

Toggleable panels beside the chart (position set by **Panel Position**): **Book** (order book), **HTF** (higher-timeframe EMA analysis), **Tips** (AI tip), and a data panel cycling **Overview** (HTF / OI / Funding / Fear-Greed), **Economic Calendar**, **Liquidation Data** (max-pain 24h/3d/7d/30d + heatmaps), **Hyperliquid whale data**, and **ETF Flows**. Panels can be re-ordered by dragging, minimized, or popped out into an expanded window (blocked popups show *"Please allow popups to open the expanded data window"*). HTF/Tips/data panels require a connected BloFin account (locked with a 🔒 otherwise). Price alerts on MA / CME gap / liquidation / news conditions can be armed from the alerts panel.

---

## Order form

### Connection and accounts

Until an exchange is linked you see **Connect Blofin API**. Once linked, the header shows **✓ Blofin Connected** (or **// CONNECTED** with **// BALANCE**) plus a **Disconnect** / **DISC** button. Below it, the account switcher lets you add extra BloFin accounts (via OAuth or manual API key / secret / passphrase with a connection test and UID verification), rename them, and switch: switching reloads the terminal on the selected account.

### Margin mode and leverage

The top row has two dropdown buttons: **Isolated**/**Cross** and the leverage (e.g. **20X**).

- Clicking the margin button toggles Isolated ↔ Cross. The selection governs the margin mode sent on **every** order.
- **Persistence**: your margin mode choice is saved locally and restored on load; it never silently resets.
- **Post-fill verification**: about 2 seconds after each fill the terminal reads the actual position back from BloFin. If the exchange opened it under a different margin mode, you get a loud red toast, `⚠ MARGIN MODE MISMATCH: you selected ISOLATED but the position opened CROSS. Check your liquidation price NOW.` (wording matches your selection), and the UI syncs to the exchange's reality.
- The **Adjust Leverage** menu shows the current value and **Max: 150X**, preset buttons **1X 2X 3X 5X 10X 20X 30X 50X**, and a 1–150 slider. Instruments with lower caps show **(Max: N×)** next to the leverage readout.

### OPEN vs CLOSE

A two-tab strip: **OPEN** and **CLOSE [REDUCE-ONLY]**.

- **OPEN** places normal orders.
- **CLOSE** sends reduce-only market closes against your existing position. It shows **LONG:** / **SHORT:** size chips for the current symbol (or *"No open position to close for X."*), caps the quantity input and % slider at your position size, hides the TP/SL section, and swaps the buttons to **[CLOSE LONG]** / **[CLOSE SHORT]** (each disabled with tooltip *"No long/short position to close"* when that side is flat). Success toasts: `Long position closed` / `Closed <size> of long position`. Without a connected account: `Connect Blofin to close positions`.

### Order type selector

Tabs: **Market**, **Limit**, and a third dropdown tab cycling **EZ / TWAP / Grid / Vault Log / Chat** (desktop; the tab shows the active mode's name).

**Limit** adds a **Limit Price** field (with **(Current: $X)** hint); prices are tick-size rounded per instrument. Success toast: `Limit order placed at $X`. Market success: `Long position opened on Blofin` / `Short position opened on Blofin`.

### Quantity

- Unit toggle: **USDT** or the base asset (e.g. **BTC**); switching clears the field.
- Amount input (up to 4 decimals) with a 0–100% slider and **0% / 25% / 50% / 75% / 100%** quick buttons. Percentages size against your available balance at the current leverage, with fees reserved; in CLOSE mode they size against the open position.
- Summary rows: **Max (BTC)** (largest size at current leverage), **Available** (USDT, with lines like **(X TWAP reserved)**, **(X vault reserved)**, **(X agent reserved)** subtracted out), **Cost (USDT)** (required margin), and **Est. Liq (Long)** / **Est. Liq (Short)** once an amount is entered. A refresh arrow re-fetches the balance.
- Margin below BloFin's $5 minimum blocks the buttons and shows: **ERR: MARGIN_BELOW_MINIMUM**, `min: $5.00 | current: $X`.
- Other validation toasts: `Please enter a valid amount`, `Position size must be greater than 0`, `Insufficient balance (needed: X, available: Y)`, `Order size too small. Minimum is X <ASSET>`, `Instrument data not loaded. Please reconnect to Blofin.`, and `Order side missing, click Long or Short again.` if a click registers without a side.
- If BloFin rejects the order with its *position mode mismatch* error (the account is in one-way mode but the order specified a long/short side), the terminal automatically retries the identical order in one-way (`net`) mode, TP/SL and LP included, so your account's position-mode setting can't reject a valid order.

### TP/SL on entry

The **TP/SL** checkbox (OPEN mode only) reveals **Take Profit Price** and **Stop Loss Price** inputs (both **Optional**). Live **Est:** profit/loss projections appear next to each label (with a **(Short)** tag when the direction implies a short). Prices are rounded to the instrument tick size; triggers fill at market. When LP is on, the SL field is disabled and labeled **(Disabled - LP Active)** with placeholder *"LP is handling Stop Loss"*.

**Partial TP/SL for new orders**: below the TP/SL inputs, the same **Partial TP/SL [ON/OFF]** manager (see below) runs in *queued* mode, orders you add are listed as **Queued TP Orders** / **Queued SL Orders** and are placed automatically right after a market entry fills, sized against the actual filled position.

### Candle-close SL

Inside the SL block: **Trigger SL only on candle close** with a timeframe select (**5m / 15m / 30m / 1h / 4h / 1d**) and an optional dedicated price field (*"Defaults to hard SL <price>"*). The hard SL stays on the exchange as an emergency stop; the candle-close stop is armed server-side (it fires even with the page closed) and only closes the position if a candle **closes** beyond the level, helper text: *"Hard SL stays as emergency stop. Candle SL fires only on a 1h close past this level."* Toasts: `Candle-close SL armed (1h) @ <price>` or `Order placed but failed to arm candle-close SL`.

### Settings toggles

- **Liquidation Protection [ENABLED/DISABLED]** (LP): replaces your SL with an automatic stop placed 0.5% inside the computed liquidation price, on every order while enabled.
- **One-Click Trading [ON/OFF]**, ON (the default) skips the confirmation dialog. Turning it ON shows a terminal-style warning (`warning: enabling one-click trading`, *"Enabling this feature will place trades with a single click without confirmation. This can lead to accidental orders. Are you sure you want to enable?"*) with **$ confirm** / **$ cancel**. With it OFF, each order opens the **order_confirmation.sh** modal listing **SIDE / SYMBOL / SIZE / LEVERAGE / TYPE / TP / SL** and asking `> Confirm order placement? [Y/n]` with **CONFIRM [Y]** / **CANCEL [n]**.
- **DD Protection [ENABLED/DISABLED]**: Drawdown Protection. Enabling opens **Enable Drawdown Protection?**, which explains it will track your starting balance, calculate drawdown from unrealized PNL, warn past your threshold, and **pause trading for 24 hours after breach**. Settings offer **5% / 10% / 15% / 20%** presets, a **Custom %** field, **Reset Starting Balance**, and a **Starting: $X** readout. On breach, the **Drawdown Limit Breached** dialog appears ("You've exceeded your N% drawdown limit… trading will be paused for 24 hours to protect your capital") with **Acknowledge**; while paused, order buttons are disabled with the tooltip *"Trading paused until <time> due to drawdown breach"*. The toggle locks (🔒) during the pause.

### Trading-safety checks

Before an order goes out, contextual warning dialogs may ask for confirmation:

| Dialog | Trigger |
|---|---|
| **Extremely Large Position** | Order value more than 50× your balance |
| **High Leverage Warning** | Leverage above 25× |
| **FOMO Warning** | Longing after >5% 24h pump or shorting after >5% dump |
| **Overtrading Warning** | 3 trades opened within 10 minutes |
| **Revenge Trading Warning** | More than 10% of the account lost in the last 24 hours |

### Order buttons

**[OPEN LONG]** / **[OPEN SHORT]** (green/red). While submitting they read **[EXECUTING...]**; in vault mode they become **[LONG VAULT·N]** / **[SHORT VAULT·N]** where N is the depositor count.

### EZ mode (risk-based sizing)

Select **EZ** from the order-type dropdown. The panel explains: *"Define your risk/reward targets. System calculates optimal position size and uses minimum 'safe' leverage to protect against liquidation."*

1. **POSITIVE RR** presets **1 RR / 2 RR / 3 RR / 4 RR** and **NEGATIVE RR** presets **0.5 RR / 0.33 RR / 0.25 RR** link your profit and risk figures: editing one dollar amount auto-fills the other at the chosen ratio, and editing one price auto-computes the mirrored price around the current market.
2. **Limit Order Mode** checkbox adds an **Entry Price** field; otherwise entries are market.
3. **TARGET PROFIT** sentence: *"I would like to make ___ USDT if the price of BTC hits ___"*, with a live % distance readout.
4. **STOP LOSS** sentence: *"I would like to risk ___ USDT if the price of BTC hits ___"*.
5. The **CALCULATED** summary shows direction (**▲ LONG** / **▼ SHORT**, inferred from whether the profit price is above or below market), **SIZE**, **LEV**, and **MARGIN**. Sizing buffers fees + slippage and floor-rounds to the instrument's lot grid so realized loss can't exceed the requested risk; leverage targets ~50% of balance as margin, clamped to the instrument max.
6. Errors: **⚠️ STOP LOSS TOO CLOSE** (*"Stop distance too small for safe leverage"*), **⚠️ POSITION SIZE TOO LARGE** (shows *Requested*, *Max Safe*, and *"(Max N× leverage for this stop)"*), and a margin-exceeds-balance warning.
7. If LP is enabled, the calculated stop is moved to 0.05% inside the estimated liquidation price. TP and SL ride on the entry order; the position row later shows an **EZ MODE (nR)** badge.

### TWAP mode

**TWAP MODE: Time-Weighted Average Price**: *"Split your order into multiple slices executed over time. Reduces market impact and averages your entry price. Orders execute even when offline."*

- **DIRECTION**: **LONG** / **SHORT**.
- **TOTAL AMOUNT** in **USDT** or the asset.
- **DURATION (MIN)** and **SLICES** (2–100).
- **LEVERAGE** slider (1–125x).
- Validation: `Each slice must be at least 1 minute apart` and `Total margin must be at least 5 USDT`. Success: `TWAP order created`.

Slices execute server-side; live progress arrives as toasts: `✅ TWAP slice executed: BTC-USDT (3/10)`, `⚠️ TWAP paused: <symbol> - <error>`, `🎉 TWAP completed: <symbol>`. Active TWAPs appear under **Open Orders** with a progress bar, **Resume** (when paused) and **Cancel** buttons, and their allocated margin shows as **TWAP reserved** balance.

### Grid mode

**[GRID_MODE] // DCA_DISTRIBUTION**: *"Split position into N limit orders distributed across price range. Each order placed as separate limit at calculated price point."*

- **ORDER_COUNT**: min 2, max 6.
- **START_PRICE** / **END_PRICE**.
- **TOTAL_AMOUNT** in **USDT** or the asset, with a live per-order breakdown; each order's margin must be at least $5 or the buttons stay disabled.
- **LEVERAGE_MULTIPLIER** slider, optional TP and SL fields.
- Buttons **[ LONG ]** / **[ SHORT ]** place the ladder (rungs tick-size rounded, sizes lot-rounded), batching large sets with `Placing batch 1/2...` toasts and a final placed/failed summary.
- Errors: `Order count must be at least 2`, `Please enter valid start and end prices`, `Start and end prices must be different`, `Please enter a valid amount`, `Blofin API must be connected to place grid orders`, `No trading pair selected`, `No valid orders to place. Check order sizes.`, `Failed to place grid orders. Check console for details.`

### Vault mode (deployers only)

Visible to superuser accounts: a **VAULT MODE** toggle with a vault dropdown (**— Select vault —**, listing name, TVL, and depositor count). Selecting one shows **Active depositors**, **Vault TVL**, and **Mode: PROPORTIONAL**, plus the warning *"Trades will execute proportionally for all N vault depositors using their API keys."* Orders then go through a confirmation, execute your deployer order first, dispatch proportional copies to every depositor, and report `Vault: deployer order placed, X copies dispatched` (plus failures). A per-depositor results modal lists success/skip/error per user. TP/SL edits and closes on vault positions propagate to all copiers. **Vault Log** in the order-type dropdown shows the vault activity feed.

---

## Positions panel

Bottom panel tabs: **Positions(N)**, **Open Orders (N)** (regular limit orders + TWAPs), **TP/SL (N)**, **Position History**, **Assets**, plus a UTC clock. Panel controls: **AI** (opens the chat operator), **Minimize**/**Expand**, and on mobile **Full**/**Back** for full-screen. The panel is drag-resizable (height persists) and auto-sizes to its content until you resize it manually; a condensed state caps it at a slim strip.

### Positions tab

Columns: **Symbol** (side dot, leverage ×, click to switch chart), **Size/Margin**, **Entry Price**, **Mark/Liq.**, **PnL** (computed from the exchange's own uPnL, not trusted contract values), **Fees** (summed from fills history), **TP/SL**, **Actions**. Badges under the symbol: **EZ MODE (nR)**, **AI TRADE** (agent-owned), **MIXED a/b** (manual size added on top of an AI position), **VAULT TRADE**.

With more than one position a header shows **Total PnL** (with fees) and **Share All**, which renders a combined P&L card; the share icon on any row makes a single-position P&L card image.

**Header checkbox: TP→SL to BE**: when enabled (persisted to your account), the moment any TP order fills, the terminal automatically moves that position's SL to break-even (entry ±0.1%) and toasts `✓ TP hit → SL moved to BE at <price>`.

**Inline TP/SL editing**: click the TP/SL cell (pencil) to edit **TP Price** / **SL Price** with live projected +/-$ readouts; invalid levels flag **Invalid** and enforce `TP must be above current price for long positions` / `TP must be below current price for short positions` / `SL must be below current price for long positions` / `SL must be above current price for short positions`. **Confirm** replaces only the full-size TP/SL, partial orders are preserved. Success feedback: `✓ TP/SL set successfully`, `✓ TP/SL orders cleared`, `✓ No changes made`.

The editor also offers **Close on candle close**: a timeframe select (5m–1d) and a **Candle SL** price (defaults to the hard SL), with the helper *"Closes only if a 1h candle closes below <price>"*. An armed stop shows as **Active candle SL: 1h < 12345** with a **Cancel** link. Toasts: `Candle-close SL armed (1h close below 12345)` / `Candle SL save failed: <reason>`.

**Action buttons per row**:

| Button | Action |
|---|---|
| **Rev** | Reverse: closes the position, waits, reopens the same size opposite (`✓ Reversed to LONG/SHORT`) |
| **LP** | Liquidation Prevention: sets an SL 0.12% safe-side of the liquidation price (`✓ LP set at <price>`) |
| **SLBE** | Stop Loss Break Even: SL at entry ±0.1% (`✓ SLBE set at <price>`) |
| **Prtl. Close** | Opens a % input + slider (1–100, presets 25/50/75/100) and **Close** (`✓ Closed 60% of position`; sizes snap to the lot grid and never strand dust below one lot) |
| **Close** | Full close (`✓ Position closed successfully`) |
| Share icon | P&L card |

Closes are resilient: the terminal walks margin-mode and position-side variants until the exchange accepts, falling back to a reduce-only market order; only if every variant fails do you see `Failed to close position, all variants exhausted`.

**Partial TP/SL manager** (opens under a position via the TP/SL editor; header **[PARTIAL_TP_SL]**): the **Partial TP/SL [ON/OFF]** button expands a panel noting *"These are separate close orders, they do not replace your main TP/SL. Multiple allowed."* Two tabs:

- **Take Profit**: **TP Price** + **% of position** (1–100, presets **25% 50% 75% 100%**), **Add TP Order**.
- **Stop Loss**: **SL Price** + **% of position**, **Add SL Order**.

Existing orders list as **Active TP Orders (N)** / **Active SL Orders (N)** with price, % (or asset size) and a trash-can to cancel (`✓ Partial order cancelled`). Sizes are converted asset→contracts via the instrument's contract value and snapped to the lot grid, never exceeding the position. Placement auto-retries across position-side (your side, then `net`/one-way) and margin-mode variants, so an account set to one-way or a different margin mode can't reject a valid order ("position mode mismatch" handling); if every variant fails, the exchange's rejection reason is shown verbatim. Form errors: `Enter a valid TP price` / `Enter a valid SL price`, `Enter a % between 1 and 100`, `Position size too small to split at this %`. Success: `✓ Partial TP order placed` / `✓ Partial SL order placed` (button flashes **Added!**).

### Open Orders tab

Pending limit orders with cancel buttons (`Order cancelled successfully`) plus active TWAP orders (progress, **Resume**/**Cancel**: `TWAP order resumed` / `TWAP order cancelled`). In demo mode this tab lists the demo positions' TP/SL orders instead.

### TP/SL tab

All pending TP/SL trigger orders. Prices are editable inline (`TP updated to <price>` / `SL updated to <price>`) and cancellable (`TP/SL order cancelled successfully`); failures surface as `Could not find original order to update` or the exchange message.

### Position History tab

Closed positions from the exchange, with per-trade P&L card generation (share images).

### Assets tab

Balances across BloFin account types, **Spot**, **Futures**, **Funding**, **Copy Trading**, with **Total**, **Available**, **Frozen** columns, a refresh button, and a transfer button opening the **Transfer USDT** modal (**From Account**, **To Account**, **Amount (USDT)** with **MAX**). Errors: `Please fill in all fields`, `Cannot transfer to the same account`, `Invalid amount`, `Insufficient balance`, `Transfer failed`, or `Failed to fetch balances`.

---

## AI Chat on the terminal

Two entry points share the same brain:

- **AI** button in the positions panel: a conversational operator over your positions with chart access.
- **Chat Order Mode**: pick **Chat** from the order-type dropdown; the order form is replaced by a chat (**CHAT MODE** header with a back arrow, live price, and a clock icon listing **Active TWAP Orders** with **Resume**/**Cancel**).

Chat Order Mode greets with **CHAT ORDER MODE** and its capability list: place market/limit orders with TP/SL, create TWAP orders, calculate EZ mode sizing, place grid orders, draw on the chart (trendlines, levels, fibonacci, channels), and check positions/balances/pending orders. Example commands from the greeting:

- `buy 0.01 BTC at 10x`
- `short $500 with 20x, SL at 105k, TP at 95k`
- `twap buy $1000 over 20 minutes`
- `ez long: risk $50, TP at 105k, SL at 98k`
- `grid buy 5 orders from 95k to 100k with $200 at 10x`
- `draw a support line at 95k`
- `mark resistance at 102k and 105k`

The chat reads the live chart (candles, current timeframe, auto-detected support/resistance) before drawing; drawings render through the same pipeline as manual tools, and it can also create custom indicators or run PineScript onto the chart on request. EZ and grid requests reuse the terminal's own calculators, so all lot-size, fee, and safety math is identical to manual trading. Executed actions report back in-chat (e.g. `EZ BUY placed: 0.5 SOL at 12x | TP: 210 | SL: 195 | Margin: ~$45`). Failure fallback: *"Failed to get response. Try again."*

---

## Mobile layout

Phones get a dedicated layout:

- **Sticky header**: symbol button (**BTCUSDT** + chevron → full-screen symbol search), 24h % change, a chart toggle, and, with the chart open, a fullscreen button. Below: live price and **Funding** rate + countdown.
- The chart (when shown, ~42% of the viewport) is the full TradingViewChart with positions, liquidation zones, and drawing support.
- Section tabs: **Trade**, **Pos (N)**, **Overview**, **Calendar**.
  - **Trade**: connection status (**// CONNECTED** / **// DEMO**, **BAL**, **DISC**), the full order form: Market/Limit/EZ/TWAP/Chat modes, leverage, **Price (USDT)** for limits, **Amount** with % slider, **TP/SL** (with **Take Profit** / **Stop Loss** fields and projected profit), **Risk : Reward** EZ form (**PROFIT (USDT)** / **TARGET PRICE** / **RISK (USDT)** / **STOP PRICE**, **Limit Order** option, calculated **SIZE / LEV / MARGIN**), **Cost (USDT)** / **Fee (USDT)** / **Available**, and big **LONG** / **SHORT** buttons. An **Order Book** section can be toggled in.
  - **Pos**: positions plus TP/SL and open-order lists ("No TP/SL orders set", "No open orders").
  - **Overview**: **Market Stats** (Mark Price, Funding Rate), **Moving Averages** (MA50/MA200 + DIFF per timeframe), **CME Gap** (FRI CLOSE / MON OPEN / DIRECTION / GAP / STATUS / FILLED), **Long/Short Ratio** per exchange, **Open Interest** (aggregated + by exchange), **Funding Rates** (average, annualized, by exchange), **Liquidation Data** (Max Pain 24h/7d), **Hyperliquid Whale Data** (top positions and recent whale alerts).
  - **Calendar**: economic calendar and news.

---

## Tutorial

**Chart Settings → Tutorial** starts a guided overlay stepping through: **Live Chart**, **Order Type**, **Position Sizing**, **TP/SL Settings**, **Your Positions**, and **Account Selector**, with a short description at each stop.

---

## What the terminal remembers

Saved to your device (restored on every load):

- Margin mode (Isolated/Cross) and the positions panel height / minimized / condensed / full-screen state.
- Chart split mode, per-chart symbols, and per-chart timeframes; last timeframe per symbol; custom minute timeframes.
- Heikin-Ashi, grid lines, light mode, ticker bar, panel side, and every overlay toggle (EMAs, period opens, liquidation levels, smart overlays, CME lines, TP/SL lines, PNL display, entry price, trade line, open orders, halving marks) plus overlay settings (deviation configs, P&L pill position).
- One-Click Trading, Liquidation Protection, active side panels and their order, orderbook/secondary tab choices, Drawdown-settings expansion, and chat mode.

Saved to your account (follow you across devices):

- Chart drawings (per symbol, shared across timeframes).
- Custom indicators, PineScript scripts, and workshop drafts.
- The **TP→SL to BE** setting, candle-close stops, Drawdown Protection settings, TWAP orders, and additional exchange accounts.

## Start free

Central Command is free when you connect your BloFin account in one click, or open one through our referral link, for as long as you trade through us. Or take the 10-day free trial: no card, no wallet, nothing renews.

1. Create an account at https://centralcommand.io/signup.
2. Choose **Free with BloFin** and connect BloFin in one click (no BloFin account yet? open one at https://partner.blofin.com/d/centralcommand), or choose the **10-day free trial**.
3. Trade from the terminal at https://centralcommand.io/dataterminal, or describe a strategy in plain English at https://centralcommand.io/agents/new: backtest it, run it on paper, and go live when you choose.

BloFin's normal trading fees still apply. Central Command trades BloFin perpetual futures only.
