# VarianTrade Documentation

A practical guide to setting up risk-controlled trading workflows from Telegram.

## What is VarianTrade

### Introduction

VarianTrade is a Telegram-native trading companion designed to interface with MetaTrader 5. The platform allows you to monitor financial markets, receive trading signals, and execute trades directly from the Telegram interface.

By operating entirely within Telegram, VarianTrade removes the necessity of installing additional trading applications or navigating complex web dashboards. It bridges systematic market analysis with automated and manual execution.

### System architecture

The platform operates on a structured flow that prioritises risk control over speed. Every trade follows a strict, sequential pipeline:

1. **Signal generation**: Trading strategies scan markets and generate a technical signal specifying entry, stop-loss, and target exit parameters.
2. **Independent review**: The signal undergoes a separate verification stage to assess validity and check for adverse market conditions.
3. **Risk limit verification**: Before reaching your broker, the trade is checked against your configured personal risk profile parameters.
4. **Execution**: If all checks pass, the order is routed to MetaTrader 5.

### The fail-closed principle

VarianTrade is built on a fail-closed design philosophy. If any validation stage in the pipeline fails to reach a verdict, or if the independent review service is offline, the system halts execution.

Missing a trading opportunity is a recoverable event, whereas executing an unreviewed position with unverified risk exposure is not. For this reason, the platform will always choose to block a signal if the second-stage check is incomplete.

### Intended audience and boundaries

VarianTrade is a utility for systematic execution and risk management. It is designed for individual traders who want to maintain strict risk parameters on their execution paths.

- **Not a signal group**: The platform does not serve as a promotional alert channel or a tip service.
- **Not a managed fund**: You retain custody of your capital at all times with your MetaTrader 5 broker. VarianTrade does not pool capital, hold user deposits, or manage funds.
- **No profit guarantees**: Trading leveraged financial instruments carries a high risk of capital loss. The platform provides risk control mechanisms, but it does not offer performance promises, profitability projections, or financial advice.

## Getting started

### First steps

To begin using the platform, search for the Telegram handle `@VarianTradeBot` and send the `/start` command.

Your Telegram account serves as your unique identity. You do not need to register a separate email address or password to access the platform or run simulated trades. Your settings and active configurations are tied directly to your Telegram chat identifier.

### Account initialization

When you invoke `/start` for the first time, VarianTrade initializes a free profile for you. The bot performs the following setup steps:

1. **Profile creation**: Registers your Telegram ID in the database and assigns a basic tier profile.
2. **Onboarding tour**: Displays an overview of system capabilities and prompts you to configure your local timezone. Configuring your timezone ensures that morning market briefs arrive at the correct local hour.
3. **Initial scan**: Triggers a demo scan of the markets to display sample opportunities.

### Recommended setup sequence

For safety and stability, you should follow this structured sequence before executing live market trades:

1. **Simulate first**: Run the system in paper mode to understand how signals align with your risk tolerances.
2. **Manual execution**: Review signals as they arrive and confirm trade execution manually via the interactive Telegram buttons.
3. **Automated execution**: Transition to auto-trading only after verifying that your risk settings perform as expected under live market conditions.

### Command reference

The table below outlines the core commands available within the chat interface:

| Command           | Action                                                        | Scope              |
| :---------------- | :------------------------------------------------------------ | :----------------- |
| `/start`          | Starts the bot and displays the main menu                     | Session management |
| `/help`           | Lists all available commands and services                     | Reference          |
| `/status`         | Shows connected broker status, balance, and subscription tier | Account            |
| `/signals`        | Displays the latest generated signals                         | Trading            |
| `/scan`           | Triggers a fresh market scan across supported assets          | Analysis           |
| `/portfolio`      | Lists active open positions and live unrealised P&L           | Trading            |
| `/paper`          | Displays simulated shadow trading performance                 | Simulation         |
| `/pause`          | Disables automated trade execution immediately                | Automation         |
| `/resume`         | Enables automated trade execution                             | Automation         |
| `/settings`       | Displays and updates timezone, daily briefs, and alert rules  | Settings           |
| `/profile`        | Shows trading style and risk parameter limits                 | Risk               |
| `/ai_connections` | Manages external AI or MCP developer credentials              | API                |

## Connecting a broker

### Setup execution

To route signals to a real account, you must link your own broker. VarianTrade uses MetaTrader 5 (MT5) for all execution paths.

1. Send the `/broker` command to `@VarianTradeBot` to open the connection menu.
2. Select the MetaTrader 5 option.
3. The bot will guide you through entering your connection parameters:
   - **MT5 Server**: The server address provided by your broker (e.g. `ICMarketsSC-MT5-4`).
   - **MT5 Login**: Your account number.
   - **MT5 Password**: The trading password associated with the account.

### Security and credential storage

VarianTrade is designed to protect your broker access details:

- **Encryption at rest**: All credentials, passwords, and keys are encrypted using secure cryptographic functions before being written to the database.
- **No plaintext exposure**: Plaintext credentials are never displayed back in the chat interface, and they are invisible to system administrators and support staff.
- **Never paste in chat**: You must never type or paste your credentials or API keys into ordinary chat sessions or public groups. All credentials must be entered only when prompted by the specific setup flow.

### Permission scopes

The broker connection operates under restricted scopes to limit potential exposure:

- **Read and trade access**: The system requires permissions to query account equity, monitor open positions, fetch history, and submit new trade orders.
- **No withdrawals**: VarianTrade does not request, store, or support withdrawal credentials. It is physically impossible for the platform to transfer or withdraw funds from your broker account.

### Unlinking your broker

You can disconnect your broker at any time. To unlink:

1. Send the `/broker` command and select the active connection.
2. Confirm the removal, or use the `/unlink` command to clear the Telegram association entirely.
3. Disconnecting your broker immediately terminates all active monitoring, halts automated execution paths, and stops signal notifications for that broker.

## Risk limits

### Execution-time enforcement

VarianTrade enforces strict risk parameters directly on the execution path. Unlike advisor alerts that warn you after a breach, the platform validates all risk parameters _before_ an order is generated and transmitted to MetaTrader 5.

If any proposed trade violates a configured threshold, the order is blocked at the system boundary. This check prevents fat-finger errors, excessive position sizing, and trading during periods of high drawdown.

### User risk profile fields

Your risk profile consists of several parameter fields that define your execution boundaries. You can view these fields using `/profile` and modify them via the `/settings` subcommands:

| Parameter Field               | Default Value | Description                                                                                                                                         |
| :---------------------------- | :------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------- |
| `max_position_size_percent`   | 10.0%         | The maximum percentage of account equity allocated to a single trade. Used to compute order quantity.                                               |
| `max_daily_drawdown_percent`  | 5.0%          | The maximum allowed daily loss (realised and unrealised) as a percentage of starting equity. If breached, further trading is suspended for the day. |
| `max_open_positions`          | 10            | The maximum number of concurrent open positions. New signals are blocked if this count is reached.                                                  |
| `default_stop_loss_percent`   | 2.0%          | The default stop-loss percentage applied to any trade if the originating signal does not specify a stop-loss price.                                 |
| `default_take_profit_percent` | 5.0%          | The default take-profit percentage applied if the signal does not specify a target exit.                                                            |
| `risk_level`                  | "moderate"    | General risk intensity level (conservative, moderate/balanced, aggressive) that influences sizing calculations.                                     |
| `auto_close_on_loss`          | True          | Boolean toggle. When enabled, the system automatically triggers a market order to close a position when it hits its designated loss threshold.      |
| `enable_risk_monitoring`      | True          | Boolean toggle. Enables continuous, real-time monitoring of open positions to detect drawdown limit breaches.                                       |

### Sizing and allocation controls

In addition to the core risk profile fields, auto-trading settings introduce controls to partition your account equity:

- **Trading allocation percentage**: By default, this is set to 100.0%, meaning the system sizes positions against your entire broker balance. You can reduce this percentage to hold a portion of your capital in cash, making it invisible to the position-sizing engine.
- **Sizing mode**: You can choose between `risk_based` sizing (sizing based on a fixed percentage of your allocation) or `kelly` sizing (sizing derived dynamically from your live trade history using the fractional Kelly criterion, falling back to risk-based sizing if you do not have sufficient historical trade data).

## Paper mode

### Overview

Paper mode is a simulation environment that is enabled by default when you initialize your VarianTrade profile. It executes trades against a virtual shadow portfolio rather than routing live orders to MetaTrader 5.

Using paper mode allows you to observe how signals interact with your chosen risk parameters under live market conditions without exposing your capital to risk.

### Simulated versus real environments

Paper mode runs the identical analytical pipeline as live trading, but execution is simulated:

- **What is simulated**: Order fills, entry prices, stop-loss triggers, target exits, and P&L calculations are simulated using current market bid/ask spreads. No real money or broker execution takes place.
- **What is real**: The market data feed, your risk limits (such as max positions and drawdown limits), news filter exclusions, and alert conditions are all active and real.

### Verifying your active mode

To confirm whether your profile is executing paper trades or live broker orders, check the status flags in Telegram:

- Send the `/status` command to view your active broker connection. The bot will print your current environment as either `Demo` (Paper) or `Live`.
- Send the `/paper` command to view your simulated shadow portfolio, listing open shadow positions, historical wins/losses, and total simulated P&L.

### How to switch modes

To switch from paper simulation to live execution:

1. Connect a live MT5 broker account by sending the `/broker` command.
2. If your connected account is configured as a demo account, execution remains in paper mode. To go live, ensure you link your live MT5 credentials.
3. Switch your automation setting on by issuing `/resume`. The confirmation message will show whether VarianTrade is active on a Demo or Live environment.

### Why to remain in paper mode

You are encouraged to keep paper mode active for at least two weeks when starting. This period allows you to:

- Observe the frequency of signals across different strategies.
- Verify that your risk allocation percentage and position sizing are comfortable.
- Inspect how the economic news filter behaves around high-impact events without risk of capital loss.

## Understanding signals

### Signal payload structure

Every signal generated by the platform contains a complete technical setup. VarianTrade does not publish raw directions; instead, each signal includes:

- **Asset**: The specific financial instrument (e.g. `EURUSD`, `BTCUSD`).
- **Direction**: Either a `BUY` or `SELL` action.
- **Entry price**: The target price level at which the trade should be entered.
- **Stop loss**: The exact invalidation price where the position will be closed to limit losses.
- **Take profit**: The target price level where the position will be closed to lock in profits.
- **Strategy**: The technical strategy that triggered the alert (e.g. `rsi_hook`, `golden_cross`).
- **Confidence**: A numeric percentage score representing model alignment.

### Confidence scores

The confidence score is a percentage indicator calculated during the generation stage:

- **What it represents**: A summary of technical factors, historical backtest alignment, and momentum evidence that support the setup.
- **What it does NOT represent**: A probability of profit, win-rate projection, or a guarantee of a positive trade outcome. It is a mathematical score of indicator convergence, not financial advice.

### The two-stage review pipeline

To prevent executing false breakout signals or trading into illiquid spreads, VarianTrade uses a two-stage verification gate:

1. **System A (Generation)**: Evaluates technical indicators, charts, and patterns to propose a new setup.
2. **System B (Verification)**: An independent review stage that evaluates the setup against macro data, economic news, and structural market conditions.

If the verification stage is offline, busy, or cannot reach an explicit positive verdict, the signal fails closed and is blocked from execution.

### Economic news filter and blackout windows

High-impact macroeconomic announcements can cause broker slippage, wide spreads, and unpredictable volatility. To mitigate these risks, VarianTrade features an economic news filter:

- **Blackout windows**: When the news filter is enabled (using `/settings news on`), the system defines a blackout window around high-impact events listed in the economic calendar.
- **Suspended trading**: Signal generation and auto-trading are suspended during these windows (typically 30 minutes before and after the release). This protects your account from sudden price spikes and spread expansion.

## Executing trades

### Execution methods

VarianTrade supports two execution methods: manual approval and fully automated trading. Both methods run through the identical risk verification pipeline before reaching your broker.

### Manual confirmation flow

In manual mode, signals are pushed to your Telegram chat as interactive cards:

- Each card displays the full setup, including the calculated position size based on your current account equity.
- To execute, you must tap the **Execute** button on the card.
- If you tap the button, the system verifies your risk limits and immediately transmits the order to your connected MetaTrader 5 broker.

### Automated trading

When automated trading is active:

- The system scans markets at set intervals, generates signals, and runs them through the two-stage review gate.
- Signals that pass the review gate and exceed your minimum confidence threshold are executed immediately without requiring manual approval.
- You can toggle automation using the `/pause` and `/resume` commands.

### The AI proposal model

VarianTrade can be connected to external AI systems or local developer tools via Model Context Protocol (MCP). Under this architecture:

- **AI cannot place trades**: The system has no execution API tools exposed to external AI connections. The `propose_trade` tool only records a trade proposal.
- **Explicit approval required**: When an AI proposes a trade, it generates a confirmation card in your Telegram chat. The order will never execute until you manually tap the confirmation button in Telegram. All proposals expire if not confirmed within their validity period.

### Closing positions

You can manage and close open positions directly from the chat interface:

- Send the `/portfolio` command to view your active positions.
- Each open position is displayed with a **Close** button.
- Tapping **Close** triggers an immediate market order on your MT5 broker to exit the position.

## Portfolio and performance

### Portfolio monitoring

You can track active positions, simulated paper trades, and historical metrics directly from Telegram. VarianTrade retrieves live data from your connected MetaTrader 5 account to construct a detailed record of execution efficiency.

### Core monitoring commands

The chat interface supports dedicated reporting commands to inspect performance metrics:

- `/portfolio`: Lists your active open positions, entry prices, current prices, and live unrealised P&L.
- `/accuracy`: Displays signal resolution stats, tracking outcomes across individual assets.
- `/perf`: Displays the performance metrics and historical track record of the VarianTrade system account.
- `/myperf`: Displays your personal trading account metrics, closed trade counts, and realised win/loss statistics.

### Tracked performance metrics

Every order routed through VarianTrade is tracked to record its exact execution path. The system monitors the following metrics to evaluate trade efficiency:

- **Signal outcomes**: Every signal is followed until it resolves to one of four states: `pending`, `won`, `lost`, or `expired`.
- **Achieved risk-to-reward**: The actual realised risk-to-reward ratio is measured against the initial projected ratio at signal generation.
- **Slippage**: The difference between the requested entry price and the broker's real fill price.
- **Maximum Adverse Excursion (MAE)**: The maximum unrealised loss experienced by the position during its lifetime.
- **Maximum Favorable Excursion (MFE)**: The maximum unrealised profit experienced by the position during its lifetime.

### Empirical performance tracking

VarianTrade measures and tracks real outcomes rather than presenting hypothetical or theoretical backtest calculations. By logging every entry, exit, and excursion, the platform measures strategy performance empirically. This focus on measured metrics ensures that your performance logs reflect actual execution history.

## Auto-Trade Configuration

### Auto-Trade Functionality

Auto-Trade allows you to automatically execute trades on your connected broker account from AI-generated trading signals. When the system detects a signal that meets your custom criteria, it calculates the appropriate size and sends the order directly to MetaTrader 5 without requiring manual confirmation.

You can customize your AI configuration settings to match your preferences:

| Setting                    | Default Value | Description                                                    |
| :------------------------- | :------------ | :------------------------------------------------------------- |
| **Trading Style**          | Intraday      | The duration and approach of trades (e.g., intraday).          |
| **Minimum Risk-to-Reward** | 1.5           | The minimum target profit relative to the risk.                |
| **Minimum Confidence**     | 70            | The minimum confidence percentage required to trigger a trade. |
| **News Filter**            | Disabled      | Toggles whether trades are blocked near major news events.     |
| **Sentiment Weight**       | 0.5           | The weight given to market sentiment analysis.                 |

### Activation and Control

Auto-trading is managed entirely through user preferences via the Telegram bot @VarianTradeBot.

- **Enable/Resume**: Set the toggle to active to resume automated order execution.
- **Disable/Pause**: Set the toggle to inactive to pause all automated execution. When paused, the bot will notify you of signals but will not place orders.

You can also restrict trading to specific instruments by adding them to the allowlist in your settings. If the allowlist is empty, all supported symbols are eligible for execution.

### Safety Guards and Refusals

To protect your capital, the execution engine enforces strict risk parameters on all automated flows. The system will refuse to execute trades in the following scenarios:

#### Position Stacking Protection

The system will never stack onto an existing open position for automated, signal, scheduled, or copy trade sources. This prevents the bot from scaling into a single instrument and creating large, unhedged exposures.

#### Concurrent Position Ceiling

A hard ceiling of 8 simultaneously open positions is enforced per account for all automated flows. No new trades are opened if this limit is reached.

#### Daily Loss Circuit Breaker

If the realized losses on your account for the day reach 6% of your total equity, the daily-loss circuit breaker trips. Automated trading is immediately halted until the next UTC day. Manual trades are exempt from this limit.

#### Per-Symbol Kill-Switch

If a specific symbol experiences 3 consecutive losses, the per-symbol kill-switch halts trading on that instrument for a 24-hour cool-off period. This isolates underperforming assets without affecting the rest of your portfolio.

#### Wallet Credit Requirements

For live accounts, the system verifies your wallet balance. If your wallet balance is zero or negative, automated trading and copy trading are blocked until the balance is topped up. Paper trading accounts are exempt from this check.

## Copy Trading

### Copy Trading Overview

Copy trading enables you to mirror the trading activity of a leader account (a strategy or another trader) on your own connected broker account. Rather than executing trades manually, the copy trading engine detects when the leader opens or closes a position and executes a corresponding trade on your account.

Every copy trade runs in isolation. A failure in executing a trade for one follower does not affect other followers copying the same leader.

### Custom Copy Parameters

When subscribing to a leader, you configure your own risk controls. These parameters ensure you remain in control of your account exposure:

| Parameter          | Type        | Description                                                                                                                                 |
| :----------------- | :---------- | :------------------------------------------------------------------------------------------------------------------------------------------ |
| **Ratio**          | Multiplier  | Position size multiplier. For example, a ratio of 0.50 means if the leader opens a 1.0 lot trade, you copy it at 0.50 lots.                 |
| **Notional Cap**   | USD Amount  | The maximum allowed USD value for any single order. If the calculated position size exceeds this cap, the size is reduced to match the cap. |
| **Daily Loss Cap** | USD Amount  | The maximum loss you are willing to incur on copied trades in a single day.                                                                 |
| **Allowlist**      | Symbol List | Optional list of symbols. If set, only trades in these symbols are copied.                                                                  |
| **Blocklist**      | Symbol List | Optional list of symbols. Trades in these symbols are never copied, even if opened by the leader.                                           |

#### Your Limits Take Precedence

Your custom limits, risk configurations, and account balances apply to all copied trades. The leader’s parameters (such as their stop-loss sizes, account equity, or leverage) do not dictate your risk. If the leader places a trade that violates your allowlist, blocklist, notional cap, daily loss cap, or broker limits, the trade is blocked on your account while the leader's trade executes unaffected.

### Safety and Validation Checks

Before any copy trade is executed on your account, the engine verifies the following rules:

- **Active Connection**: You must have an active broker connection configured.
- **Instrument Restriction**: The symbol must pass both your custom allowlist and blocklist validations.
- **Daily Loss Threshold**: If your cumulative closed losses for the day meet or exceed your daily loss cap, new copy trades are blocked.
- **Transaction Frequency Ceiling**: To prevent runaway loops, a safety limit of 100 trades per day is enforced for copy trading.
- **Wallet Credits**: You must maintain a positive balance in your wallet. If your balance is zero or negative, copy trading execution is suspended.

### Stopping and Pausing

You can manage your copy subscriptions at any time through the Telegram bot. To stop copying a leader:

1. Open the subscription settings menu.
2. Select your active copy trading subscription.
3. Toggle the subscription status to inactive or select delete to remove the relationship entirely.

## Managed Accounts

### Managed Accounts Overview

Managed accounts allow you to delegate trading decisions to an allocated trader or automated strategy. Your funds remain in your custody under your broker account while trades are executed on your behalf.

When setting up a managed account, you select a name and allocate capital. You also assign a defined risk level:

- **Low**: Conservative risk parameters focusing on capital preservation.
- **Medium**: Balanced risk parameters matching standard market conditions.
- **High**: Aggressive risk parameters seeking higher returns with higher volatility.

### The High-Water Mark Fee Structure

Performance fees are calculated using a High-Water Mark (HWM) mechanism. This structure ensures that a profit share is only charged on net new profits. If the account loses value, no performance fees are charged until the losses are fully recovered and the account value exceeds its previous peak.

The performance fee is calculated as a profit share percentage (e.g., 20%) applied to the net gain above the highest historical account value recorded (the high-water mark).

#### Hypothetical Illustration of High-Water Mark Calculations

The following scenario is a hypothetical illustration to demonstrate how the high-water mark is calculated and updated. It is not a representation of actual performance or a guarantee of profits.

Assume a managed account is established with a 20% profit share fee rate.

1. **Initial Allocation**:
   - You allocate **$10,000** to the strategy.
   - The initial High-Water Mark (HWM) is set at **$10,000**.

2. **Period 1 (Growth)**:
   - The account value increases to **$11,000** at the end of the billing period.
   - Net profit is **$1,000** ($11,000 current value - $10,000 HWM).
   - The 20% performance fee is calculated on the $1,000 profit: **$200** ($1,000 * 20%).
   - The fee is deducted, leaving a balance of **$10,800**.
   - The new HWM is updated to the post-fee peak of **$10,800**.

3. **Period 2 (Market Decline)**:
   - Market volatility causes the account value to drop to **$9,500**.
   - No performance fee is charged because the value ($9,500) is below the HWM ($10,800).
   - The HWM remains at **$10,800**.

4. **Period 3 (Partial Recovery)**:
   - The account value recovers to **$10,500**.
   - Although the account gained $1,000 during this period (rising from $9,500 to $10,500), the current value ($10,500) is still below the HWM ($10,800).
   - No performance fee is charged.
   - The HWM remains at **$10,800**.

5. **Period 4 (New Peak)**:
   - The account value rises to **$11,500**.
   - Because the value exceeds the HWM of $10,800, a fee is due on the net new profit.
   - Net new profit is **$700** ($11,500 current value - $10,800 HWM).
   - The 20% performance fee is calculated on the $700 net new profit: **$140** ($700 * 20%).
   - The fee is deducted, leaving a balance of **$11,360**.
   - The HWM is updated to the new peak of **$11,360**.

Through this system, you only pay performance fees when the strategy generates new net gains, and you never pay fees on the same gains twice.

## Historical Backtesting

### Backtesting Overview

Backtesting allows you to simulate how a trading strategy would have performed using historical market data. By running a strategy over historical periods, you can analyze performance metrics, drawdown characteristics, and execution behaviors before deploying capital.

The platform supports historical backtesting for key strategies including:

- **GoldenCross**: A simple moving average crossover.
- **EMACross**: An exponential moving average crossover.
- **RSI**: An RSI hook entry logic with EMA-50 confirmation.
- **MACD**: A MACD signal line crossover.
- **BollingerBands**: A mean reversion strategy based on statistical bands.
- **Momentum**: A short-lookback momentum strategy.
- **Scalping**: A high-frequency strategy with tight stops and quick targets.
- **MTF**: A multi-timeframe strategy combining daily, 4-hour, and 1-hour indicators.
- **Variants A-D**: Advanced strategy rules combining technical indicators and Fibonacci retracements.

### Performance Metrics

When a backtest completes, the system provides several key metrics:

| Metric                | Description                                                                         |
| :-------------------- | :---------------------------------------------------------------------------------- |
| **Total Return**      | The cumulative percentage gain or loss over the test period.                        |
| **Annualized Return** | The geometric progression rate that measures return on an annual basis.             |
| **Sharpe Ratio**      | A measure of risk-adjusted return, indicating excess return per unit of volatility. |
| **Sortino Ratio**     | Similar to Sharpe, but only penalizes negative volatility (downside risk).          |
| **Max Drawdown**      | The largest peak-to-trough decline in capital during the test period.               |
| **Profit Factor**     | The ratio of gross profits to gross losses.                                         |
| **Win Rate**          | The percentage of trades that closed in profit.                                     |
| **expectancy_r**      | The average R-multiple (risk unit) expectation per trade.                           |
| **SQN**               | System Quality Number (Van Tharp SQN) measuring system reliability.                 |

### Walk-Forward Validation

To prevent optimization bias (overfitting), the platform provides Walk-Forward Validation. This process splits your historical dataset into:

1. **In-Sample Window (Training)**: The strategy parameters are optimized to fit the historical data.
2. **Out-of-Sample Window (Testing)**: The optimized parameters are evaluated unmodified on untouched data.

This split helps verify whether the strategy's edge is robust or simply fit to historical noise. The validation returns a **kill_criterion** status based on the out-of-sample System Quality Number (SQN):

- **Kill**: If the out-of-sample SQN is below 1.6, the strategy’s edge is indistinguishable from random market noise.
- **Insufficient Sample**: If the backtest results in fewer than 30 trades, the sample size is too small to draw a statistically significant conclusion.

### Comparing Backtests and Live Behavior

While backtesting is a valuable diagnostic tool, it is critical to understand its limitations:

#### What Backtesting Cannot Tell You

- **Past Performance is Not Predictive**: Market conditions shift. A strategy that performed exceptionally well during a trending period may fail during a range-bound market.
- **Overfitting Risk**: It is easy to tweak parameters until a backtest looks perfect. This is curve-fitting, and it frequently results in poor performance in live markets because the settings are optimized for past noise rather than structural edges.
- **Execution Mismatches**: Backtests assume perfect execution. In live environments, your results will differ due to factors not fully modeled in basic tests:
  - **Slippage**: The difference between the expected execution price and the actual fill price.
  - **Spread**: The difference between the buy and sell prices.
  - **Latency**: Delay in signal delivery or broker order routing.
  - **Fill Quality**: Partial fills or rejections on large orders.

#### Scorecard Comparison

The platform provides a live vs. backtest scorecard. This scorecard compares the live shadow-mode performance of a strategy with its historical backtest record over the same timeframe.

The **win_rate_drift_pct** metric measures the difference between the live win rate and the backtest win rate. A significant negative drift indicates that the strategy edge is being degraded by live execution costs (such as spreads and slippage) rather than flawed logical rules.

## Market Context

### Market Sentiment Scoring

The sentiment engine aggregates news, social media, and market news sentiment to calculate an overall mood score for supported assets. The engine uses a combination of data sources:

- **NewsAPI**: Aggregates and filters major news headlines.
- **Google News (RSS)**: Integrates global RSS financial news feeds.
- **StockTwits**: Measures retail social media sentiment.
- **Alpha Vantage**: Incorporates publisher-attributed news sentiment.

Under standard conditions, these four sources are weighted equally (25% each) to produce a composite score.

#### Adaptive Weighting and Health Checks

The engine monitors the health of each API source. If a source experiences errors or rate limits (e.g., HTTP 429), it is down-weighted dynamically during the health window (1 hour). After the hour passes without further errors, the source recovers its full weight. This ensures transient outages do not skew overall sentiment.

#### Time-Decay and Timeframe Restrictions

- **Time-Decay**: Newer articles carry more weight than older ones, decaying with a half-life of 48 hours.
- **Backtesting Isolation**: When running backtests, only historical news sources (like Alpha Vantage) are queried for the specified historical window. This prevents lookahead bias (mixing today's headlines into historical simulations).

#### Threshold Classifications

The sentiment score ranges from -1.0 (strongly bearish) to +1.0 (strongly bullish). The thresholds differ based on asset class volatility:

| Asset Class      | Strong Bearish | Bearish            | Neutral            | Bullish            | Strong Bullish |
| :--------------- | :------------- | :----------------- | :----------------- | :----------------- | :------------- |
| **Crypto**       | $\le -0.40$    | $-0.40$ to $-0.10$ | $-0.10$ to $+0.10$ | $+0.10$ to $+0.40$ | $\ge +0.40$    |
| **General/Fiat** | $\le -0.25$    | $-0.25$ to $-0.10$ | $-0.10$ to $+0.10$ | $+0.10$ to $+0.25$ | $\ge +0.25$    |

The engine also tracks a 24-hour linear regression trend to classify the sentiment trajectory as **improving**, **deteriorating**, or **stable**.

### Economic Calendar and Indicators

The economic engine monitors key macroeconomic data points from the FRED database. These indicators provide macro regime context to the trading algorithms:

- **CPIAUCSL**: Consumer Price Index (Inflation).
- **PCEPI**: Personal Consumption Expenditures Price Index (Inflation).
- **FEDFUNDS**: Federal Funds Effective Rate (Monetary Policy).
- **DGS10 / T10Y2Y**: 10-Year Treasury Yield and the Yield Curve spread.
- **GDP**: Gross Domestic Product (Growth).
- **UNRATE / PAYEMS**: Unemployment Rate and Nonfarm Payrolls (Labor Market).

The engine determines the overall market regime (e.g., overheating, stagflation, recession, goldilocks, easy money, or transitional) based on these macroeconomic trends.

### News Filters and Trade Blocking

Users can enable the **News Filter** in their auto-trade settings. When active, this filter acts as a check before opening new automated positions.

- **Macro Blocker**: If the economic engine detects a transition to high-volatility regimes (such as an impending high-impact FOMC rate decision or CPI release), it can flag upcoming calendar events.
- **Sentiment Block**: If the composite sentiment score for a specific asset is contrary to the signal direction (e.g., a buy signal occurs while the asset's sentiment is "Strongly Bearish"), the execution engine blocks the trade.

## Alerts and Notifications

### Price and Indicator Alerts

You can configure real-time alerts for price movements and technical indicator levels directly in Telegram using the bot @VarianTradeBot.

#### Setting Alerts

To set an alert, use the `/alert` command followed by your alert conditions in plain English. The bot uses a fast AI parser to extract the target asset, trigger condition, and threshold.

Supported conditions include price thresholds and technical indicators:

- `/alert BTC below 90000` (price drops below 90,000)
- `/alert EURUSD above 1.12` (price rises above 1.12)
- `/alert ETH RSI under 28` (RSI drops below 28)

Once confirmed, the bot will monitor the asset and notify you immediately when the condition is met.

#### Managing Alerts

To view and manage your active alerts, use the `/alerts` command. This will output a list of your configured alerts. You can cancel individual alerts or clear all alerts using the inline keyboard buttons:

- **Cancel**: Deactivates a specific alert.
- **Cancel All**: Deactivates all active alerts on your account.

### One-Shot Reminders

In addition to price alerts, you can set one-shot reminders for specific actions or market scans.

#### Staging Reminders

Reminders are staged interactively within your chat. By telling the AI to set a reminder (e.g., "remind me Monday at 9am to check BTC" or "remind me in 2 hours to scan the market"), the bot parses the request and prompts you with a confirmation button. Reminders expire if not confirmed within 15 minutes.

#### Reminder Types

- **Signal Check**: A standard reminder message prompting you to review current signals.
- **Opportunity Scan**: A one-time automated scan of the market for trading setups executed at the designated time.

### Controlling Notification Preferences

You can customize what notifications you receive to prevent alert fatigue.

- **Proactive Signals Toggle**: You can enable or disable proactive signal alerts via your settings menu (using the "Enable alerts" or "Mute alerts" options).
- **Mute Safety Exceptions**: Toggling off proactive signal alerts will **not** mute reminders you explicitly requested, daily market briefs, or critical account/security updates. These essential messages bypass the mute setting.

## Subscriptions and Credits

### Subscription Plans

VarianTrade is one product sold over three terms. The paid plans unlock the same
features and share the same allowances — what differs is how long the payment
buys. Payments are processed by Bachs, which accepts cards and bank transfer.

| Plan        | Price      | Term              | Monthly credits | Broker accounts |
| :---------- | :--------- | :---------------- | :-------------- | :-------------- |
| **Free**    | $0         | —                 | 0               | None            |
| **Trial**   | $15 USD    | One week, one-off | 500             | 3               |
| **Monthly** | $54.99 USD | Per month         | 500             | 3               |
| **Yearly**  | $499 USD   | Per year          | 500             | 3               |

The Yearly plan works out at $41.58 a month, saving $160.88 against twelve
monthly payments. The Trial is a single charge and does not renew.

### What the free plan includes

The free plan is not a metered version of the product. It is one feature: send a
chart, and the AI returns a recommendation with entry, stop and target, a few
times a day.

A free account **cannot** use AI chat, signals, auto-trade, copy trading or a
broker connection. Those are refused rather than metered — there is no allowance
to run down. Upgrading with `/subscribe` unlocks them.

### Daily usage quotas

AI chat and chart analysis consume real processing capacity, so each plan has a
daily allowance. Allowances reset at 00:00 UTC. Check where you stand at any
time with `/usage`.

| Plan        | AI chat      | Chart reads |
| :---------- | :----------- | :---------- |
| **Free**    | Not included | 5 / day     |
| **Trial**   | 500 / day    | 150 / day   |
| **Monthly** | 500 / day    | 150 / day   |
| **Yearly**  | 500 / day    | 150 / day   |

No plan is unmetered. Every plan has an enforced ceiling, and the figures above
are the ones the system actually applies rather than a marketing summary.

#### Quota Enforcement and Burst Guards

- **Quota Peak**: If you reach your daily limit, further requests are refused until the UTC midnight reset. You can monitor your usage with the `/usage` command.
- **Burst Guard**: To prevent runaway loops, an invisible burst limit is applied across all plans:
  - **AI Chat**: 12 requests per minute.
  - **Chart Analysis**: 4 requests per 2 minutes.
    Tripping the burst guard results in a temporary cooldown pause but does not consume your daily allowance.
- **Availability**: Quota accounting is designed so that a temporary problem on our side does not lock you out of your own account. Features your plan does not include remain unavailable regardless.

### Credit Packages

If you require additional monthly usage credits, you can purchase one-time credit boosters. These credits are added to your balance:

- **AP Booster 250**: $10 USD for 250 credits.
- **AP Booster 1000**: $30 USD for 1000 credits.

Credit packages are purchased through the same Bachs checkout and applied instantly to your account.

## Referrals and XP

### Referral System and Milestones

You can earn rewards by referring new users to VarianTrade. The system pays commissions and milestone bonuses based on qualified referrals.

#### Qualification and Hold Window

- **Qualification**: A referral counts as qualified only when the referred user registers and pays for their first subscription.
- **Hold Window**: To prevent fraud and abuse, all milestone bonuses are subject to a 14-day hold period. The status of the milestone bonus progresses from `pending_hold` to `approved` after 14 days, unless a refund or chargeback occurs, which marks the entry as `reversed`.

#### Earnings and Bonuses

- **Subscription Commission**: You earn a 20% commission on the subscription fees paid by your referred users.
- **Milestone Bonuses**: In addition to standard commissions, you receive a flat USD milestone bonus for every 5 qualified referrals:

| Qualified Referrals | Milestone Bonus | Cumulative Milestone Bonuses |
| :------------------ | :-------------- | :--------------------------- |
| **5 Referrals**     | $10 USD         | $10 USD                      |
| **10 Referrals**    | $20 USD         | $30 USD                      |
| **15 Referrals**    | $30 USD         | $60 USD                      |
| **20 Referrals**    | $40 USD         | $100 USD                     |

### Experience Points (XP) and Streaks

The platform incorporates a gamification system to encourage consistent activity. You can track your XP points, active streak, and progress toward the next milestone using the `/xp` command.

#### Earning XP

You can accumulate XP by performing standard actions:

- **Daily Check-in**: +10 XP
- **View Signals**: +5 XP
- **Execute a Trade**: +20 XP
- **Shadow Trade Profit**: +15 XP
- **Refer a Friend**: +100 XP

An active streak is maintained by performing at least one action per calendar day.

#### Unlocking Rewards

When you reach **500 XP** or maintain a **7-day active streak**, you qualify for a reward. You can claim it using the `/claim` command:

- **3-Day Trial**: If you are currently on a free plan, the `/claim` command unlocks a 3-day trial of the paid product. This grants you the paid daily usage allowance (500 chats and 150 vision checks per day), auto-trade, and priority AI chat.
- Paid subscription users are not eligible to claim the trial as they already have active paid features.

#### Limits of Gamification

XP points, levels, and active streaks are strictly gamification mechanisms. **XP does not affect trading behavior, position sizing, execution speed, or risk parameters.** All broker interactions, execution controls, and capital-at-risk limits remain governed exclusively by your account settings and connected broker specifications.

## Telegram AI Assistant

### Overview

The Telegram assistant is your primary interface for interacting with Varian. You can converse with the assistant in plain English to query market data, analyze chart images, retrieve trading signals, and check your portfolio.

### Trading Safety Boundary

The assistant is strictly an information, analysis, and proposal tool. It does not have direct execution capabilities to place trades on your broker.

When you ask the assistant to execute a trade, or when the assistant identifies a high-confidence setup, it generates a trade proposal. This proposal is displayed as a reviewable card in the chat interface. You must tap the confirmation button to execute the trade on your linked broker. This ensures you retain full control over all broker actions.

### Context and History Commands

To keep replies relevant and concise, the assistant retains a running memory of your conversation. You can manage this memory using the following commands:

#### /context

The `/context` command shows what the assistant remembers. It displays:

- The current context window usage as a percentage of the token budget.
- The number of messages currently held in active memory.
- The current summarized summary of older messages carried forward.

#### /compact or /summarize

If your conversation runs long, the assistant automatically compresses older messages. You can trigger this manually at any time by running `/compact` or `/summarize`. This keeps the active context compact and clean without losing key information from earlier in the session.

#### /clear

The `/clear` command deletes the conversational history. The assistant will start with no memory of past exchanges.

#### /usage

The `/usage` command shows your remaining conversational and chart vision allowance for the billing period.

### Interactions

You can converse with the assistant or query specific features:

- **Market Queries**: Ask for current prices, trend indicators, or general analysis of supported assets.
- **Chart Analysis**: Upload a chart image with a caption to receive an objective analysis of trend, support, resistance, and key indicators.
- **Conversational Proposals**: Describe a trade, such as "buy BTC worth $500", to generate a reviewable confirmation card.

## AI Connections Overview

### Overview

VarianTrade supports three distinct modes to connect your own AI models or applications to your account. This allows you to choose the integration that best matches your billing preferences, application compatibility, and privacy requirements.

### Comparison of Connection Modes

| Mode                 | Who Pays                                                                                    | What Leaves Your Machine                                                                                  | Capabilities                                                                                                     |
| -------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| **Remote MCP**       | You pay the provider subscription or API for your external AI application.                  | Only context retrieved by tool calls (portfolio summary, positions, risk limits, signals, market data).   | Connects an MCP-capable desktop AI application (such as Claude Desktop or Cursor) directly to VarianTrade tools. |
| **Your API Key**     | You pay the API provider (OpenAI, Anthropic, DeepSeek, or Gemini) directly for token usage. | The prompt text and context data. Your API key is transmitted once for verification and stored encrypted. | Enables the in-Telegram assistant to utilize your own API quota instead of VarianTrade credits.                  |
| **Local CLI Bridge** | You pay the provider subscription (such as Claude Pro or ChatGPT Plus) for the CLI tool.    | Prompts and text outputs. No API keys, credentials, or session cookies ever leave your machine.           | Runs AI jobs locally on your machine using your already-authenticated provider CLI tool.                         |

### Inspecting and Revoking Connections

You can view all active connections at any time by sending `/ai_connections` in Telegram. This lists the status, connection type, last seen time, and scopes of each connection.

To revoke any connection:

1. Run `/ai_connections` in Telegram.
2. Tap the **Revoke [Name]** button for the connection you want to remove.
3. Confirm the revocation when prompted.

Revocation is processed immediately: the associated access token or device secret is deleted, and the external application is blocked from making further requests.

### Security Warning

Never paste API keys, browser cookies, session tokens, or CLI credentials directly into an ordinary chat message, public group chat, or support request. VarianTrade will only prompt you for credentials in a secure, private Telegram chat during an active setup flow.

## Remote Model Context Protocol

### Overview

The Model Context Protocol (MCP) is an open standard that enables AI models to safely call local or remote tools. VarianTrade provides a remote MCP server listed in the official Model Context Protocol registry. This lets external AI editors, chat applications, and custom agents fetch real-time portfolio data and propose trades.

The remote MCP server URL is:

```
https://api.variantrades.com/mcp/rpc
```

### Tool Catalogue

The MCP server exposes seven tools, each restricted by specific OAuth scopes:

| Tool Name               | OAuth Scope      | Description / Return Values                                                                                               |
| ----------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `get_account_status`    | `account.read`   | Returns non-secret account metadata, including subscription details and verification status.                              |
| `get_portfolio_summary` | `portfolio.read` | Returns aggregated metrics: open and closed position counts, long/short counts, realized P&L, and open symbols.           |
| `get_open_positions`    | `portfolio.read` | Returns a list of active positions, including entry price, current price, stop loss, take profit, and individual P&L.     |
| `get_risk_limits`       | `risk.read`      | Returns configured risk limits, including maximum position size, daily drawdown limit, and default stop-loss percentages. |
| `list_recent_signals`   | `signals.read`   | Returns recent AI-generated trading signals, including confidence scores, entry targets, and reasoning.                   |
| `get_market_snapshot`   | `market.read`    | Returns live price snapshots, volume, and percentage change for up to five symbols.                                       |
| `propose_trade`         | `trade.propose`  | Records a trade proposal for later confirmation. Returns a proposal ID and expiration details.                            |

### Authorization and Approval Flow

When you add the remote MCP server to an external AI application, the application initiates an OAuth 2.1 authorization flow:

1. The AI application opens a VarianTrade web page displaying the requested permission scopes.
2. The page provides a link to open the VarianTrade Telegram bot.
3. In Telegram, you receive a prompt showing the application name and the exact scopes requested.
4. You select **Approve** or **Deny** in the bot chat.
5. The authorization web page refreshes and redirects the AI application to complete the connection.

### Safety Boundary

The `propose_trade` tool operates under a strict safety boundary. It only records a trade proposal; it never executes the trade or places orders directly on a broker.

Every proposal must be confirmed manually by the user within the Telegram bot using the `/trades` interface. If a proposal is not approved within 15 minutes, it expires and is automatically deleted.

### Worked Example: Tool Sequence

A well-behaved AI assistant should verify market conditions and risk limits before proposing a trade. The following sequence illustrates a sensible workflow:

1. **Verify Market Conditions**:
   `get_market_snapshot` (symbols: ["BTCUSD"])
   Returns the current market price of the asset.
2. **Retrieve Risk Profile**:
   `get_risk_limits`
   Checks the maximum position size and default stop-loss settings allowed on the account.
3. **Check Portfolio Constraints**:
   `get_open_positions`
   Ensures the new trade does not exceed the maximum allowed number of open positions or overall allocation limits.
4. **Propose the Trade**:
   `propose_trade` (symbol: "BTCUSD", side: "buy", quantity: 0.1, stop_loss: 95000, take_profit: 105000)
   Creates the proposal and returns the ID for user confirmation in Telegram.

## CLI Companion

### Overview

The CLI Companion (`variantrade-bridge`) is a local agent that executes AI jobs on your computer using provider command-line interfaces that you have already signed into. This allows you to utilize subscription services you already pay for (such as Claude Pro or ChatGPT Plus) without exposing your API keys, session tokens, or browser cookies to the VarianTrade server.

### Installation

The companion must be installed via Cargo, the Rust package manager. Pre-built binaries are not published.

To install the companion, you need a Rust toolchain (version 1.86 or newer) from [rustup.rs](https://rustup.rs). Run:

```sh
cargo install variantrade-bridge
```

### Command Reference

The companion tool supports the following commands:

#### providers

Lists the provider CLIs supported by this build and shows which ones are currently detected on your system path.

```sh
variantrade-bridge providers
```

#### enroll

Enrolls the machine with your VarianTrade account.

```sh
variantrade-bridge enroll --code <CODE> --provider <PROVIDER>
```

- `--code`: The one-time enrollment code obtained from Telegram.
- `--provider`: The CLI provider to use (defaults to `claude`).
- `--name`: Optional custom label for this device.

#### run

Starts the execution loop. The companion will poll VarianTrade for queued jobs, execute them locally, and return only the text outputs.

```sh
variantrade-bridge run --interval <SECONDS> --timeout <SECONDS>
```

- `--interval`: Poll interval in seconds when the queue is empty (defaults to 5).
- `--timeout`: Maximum seconds allowed for a single CLI invocation (defaults to 180).

#### status

Displays the local enrollment state, selected provider, server connection status, and configuration file path.

```sh
variantrade-bridge status
```

### Enrollment Process

1. In Telegram, send `/ai_connections` and tap **Use local CLI** or **Set up this computer** to generate a one-time enrollment code.
2. The code expires after 15 minutes and can only be used once.
3. Run the `enroll` command on your machine with the code.
4. The server registers the device and returns a unique device secret, which is saved locally with owner-only access permissions (`0600` on Unix systems).

### Security and Job Boundaries

The companion implements several safety features to protect your machine:

- **No Arbitrary Commands**: The application drives provider CLIs using a fixed command table defined in the source code. It does not invoke a shell (`sh -c`), preventing arbitrary command injection.
- **Credentials Stay Local**: The companion does not store or transmit your provider API keys, tokens, or session cookies. It authenticates to VarianTrade using a device-specific secret hash.
- **Single Job Execution**: The device claims and processes only one job at a time.
- **Execution Limits**: Each job is bounded by a configurable execution timeout and size caps on the inputs and outputs.
- **Sanitized Error Reporting**: If a job fails, the companion reports only a short error category (such as `max_attempts` or `timeout`) rather than the raw command output, preventing error messages from leaking sensitive context or credentials.

### Revoking a Device

You can disconnect any enrolled machine at any time:

1. Send `/ai_connections` in Telegram and navigate to your computer list.
2. Select **Revoke [Device Name]**.
3. Confirm the revocation.

The server immediately deletes the secret hash for that device. Any subsequent request from the local companion will be rejected, and any pending or running jobs for that device are cancelled.

## Varian Trading Skill

### Overview

The Varian trading skill is a free, system-level package that you can install directly into your own AI applications, such as Claude Desktop, Cursor, Codex, Copilot, or Gemini. It teaches your AI the discipline, risk management, and tool integration practices used by VarianTrade.

Installing this skill does not require a VarianTrade account, payment, API keys, or registration.

The official listing page is:

```
https://skills.sh/Chidi09/varian-trading-skill/varian-trading-skill
```

### Installation

You can install the skill into any compatible AI application or editor by running the following command in your project or home directory:

```sh
npx skills add Chidi09/varian-trading-skill
```

### AI Behavioral Rules

Once the skill is installed, it injects structured guidelines into your AI's system prompt. These guidelines enforce several strict trading habits:

- **Source and Timestamp Validation**: The AI will refuse to quote or analyze prices without referencing a verified source and a recent timestamp.
- **Risk-Based Position Sizing**: The AI is instructed to calculate position sizes based on the monetary loss you accept (your risk tolerance) rather than an arbitrary lot size.
- **Pre-Entry Invalidation**: The AI will define a clear invalidation level (stop-loss) before describing any trade entry setup.
- **Correlation Risk Management**: The AI will group highly correlated symbols together and treat them as a single exposure, preventing hidden risk concentration.
- **Proposal Safety**: The AI is instructed to propose trades for your review rather than simulating or assuming immediate execution.
- **Credential Protection**: The AI is trained to actively refuse any API keys, browser cookies, or session tokens pasted into the chat window, instructing you on safer connection routes instead.

### MCP Integration

In addition to risk behaviors, the skill teaches your AI how to locate, configure, and communicate with the remote VarianTrade Model Context Protocol (MCP) server at `https://api.variantrades.com/mcp/rpc`.

If you choose to link your VarianTrade account, this skill allows your AI to seamlessly invoke VarianTrade tools to read your portfolio, review active signals, check risk profiles, and stage trade proposals during your conversation.

## Security and Privacy

### Overview

VarianTrade is built with a user-owned model integration architecture. This design ensures that you retain ownership of your API credentials, subscription accounts, and trading decisions.

### Credential Handling and Encryption

VarianTrade does not store raw secrets or credentials inside its main application databases:

- **Decoupled Storage**: API keys, session tokens, and broker secrets are moved immediately upon submission into an isolated secret manager.
- **Opaque References**: The application databases store only a unique, random credential reference string to retrieve configuration metadata.
- **Encryption at Rest**: Any credentials stored in the secret manager are encrypted at rest using industry-standard cryptographic keys.

### Granular Scopes and Approvals

External integrations operate under a permission model called scopes. These scopes ensure that an AI application is only granted the minimum permissions necessary:

- `account.read`: Grants access to non-sensitive account metadata.
- `portfolio.read`: Grants access to open positions and realized P&L metrics.
- `risk.read`: Grants access to configured risk settings and sizing rules.
- `signals.read`: Grants access to recent trading recommendations.
- `market.read`: Grants access to fetch live price snapshots.
- `trade.propose`: Grants permission to suggest a trade proposal.

Every permission request must be approved by the user through a Telegram confirmation step before any tokens or access codes are issued.

### Immediate Revocation

You retain absolute authority to terminate any connection or device.

- **Immediate Expiration**: Revoking a connection via `/ai_connections` deletes the associated secret reference, revokes active OAuth tokens, and replaces local bridge device secrets with randomized, unusable placeholder hashes.
- **Open Job Cancellation**: Revoking a device instantly cancels any running or queued AI jobs associated with it.

### Messaging Security

To protect your accounts from credential harvesting or accidental leakage:

- **Immediate Message Deletion**: When you enroll an API key in a private Telegram chat, the bot is programmed to delete your message from the chat history immediately before validating the credential.
- **No Plaintext Prompts**: VarianTrade will never prompt you to paste broker passwords, API keys, or browser session cookies into a public group chat, support ticket, or ordinary message. All key registrations are restricted to private chats during an active configuration flow.

### Unlinking and Data Control

If you wish to disconnect your Telegram account from VarianTrade:

- **The /unlink Command**: You can run `/unlink` in Telegram to request unlinking.
- **Notification Cessation**: Confirming the request deletes the link between your Telegram account and the database, immediately halting all alerts, signal notifications, and chat actions.

## Command Reference

### Overview

The VarianTrade Telegram bot provides a set of slash commands to manage your account, monitor positions, configure alerts, and interact with the AI assistant.

### Command List

| Command           | Description                                                                                      |
| ----------------- | ------------------------------------------------------------------------------------------------ |
| `/accuracy`       | Displays win rate, achieved risk/reward, and calibration metrics for recent resolved signals.    |
| `/ai_connections` | Displays connected AI models, API keys, and local companion devices with revocation options.     |
| `/alert`          | Sets a custom price or indicator alert using natural language (e.g., `/alert BTC below 90000`).  |
| `/alerts`         | Displays active price or indicator alerts with options to cancel them.                           |
| `/broker`         | Initiates the connection flow to link or change your trading broker.                             |
| `/cancel`         | Cancels the current pending interactive setup or configuration process.                          |
| `/claim`          | Claims eligible trial subscription rewards.                                                      |
| `/clear`          | Wipes the active Telegram chat memory and starts a fresh conversation.                           |
| `/close`          | Closes your current open support ticket.                                                         |
| `/compact`        | Compresses conversation history to fit within the assistant's context limits.                    |
| `/complaint`      | Opens a new support ticket with the system.                                                      |
| `/context`        | Displays context window metrics and the active conversation summary.                             |
| `/email`          | Configures or updates your email address and notification settings.                              |
| `/help`           | Lists all available bot commands and their primary functions.                                    |
| `/link`           | Connects your Telegram bot chat to your registered VarianTrade profile.                          |
| `/myperf`         | Displays your broker-synced trading performance history and net P&L.                             |
| `/optimize`       | Calculates Sharpe-maximized allocations for your portfolio (requires at least 2 open positions). |
| `/paper`          | Displays statistics and active positions for your shadow (demo) trading account.                 |
| `/pause`          | Disables the automatic execution of trade signals on your broker.                                |
| `/perf`           | Displays Varian's overall live track record, closed trade count, and win rate.                   |
| `/portfolio`      | Displays active positions, entry levels, and real-time unrealized P&L from your broker.          |
| `/profile`        | Displays and configures your experience level, goals, and market preferences.                    |
| `/resume`         | Enables the automatic execution of high-confidence trade signals on your broker.                 |
| `/scan`           | Triggers a fresh market scan across supported assets to find new opportunities.                  |
| `/settings`       | Configures user-level settings including timezone, daily briefs, and promotional alerts.         |
| `/signals`        | Fetches the latest AI signals or configures signal push settings (e.g., `/signals on`).          |
| `/start`          | Initialises the bot, displays the welcome message, and guides you to link your account.          |
| `/status`         | Shows account details, active subscription tier, and current broker connectivity state.          |
| `/subscribe`      | Lists available subscription plans and upgrade options.                                          |
| `/summarize`      | Compresses older conversation history to free context window space (alias for `/compact`).       |
| `/unlink`         | Disconnects your Telegram account from VarianTrade, halting all alerts.                          |
| `/usage`          | Displays your remaining credit allowance for AI messages and vision tasks.                       |
| `/xp`             | Displays your accumulated XP, current rank, and login streak statistics.                         |

## Troubleshooting

### Overview

This guide provides resolutions for common issues encountered when configuring brokers, receiving signals, running AI connections, or operating the CLI companion.

### Broker Integration Issues

#### Broker Not Linked Warning

If you receive an integration warning when trying to enable auto-trading or place order proposals:

1. Send `/broker` in Telegram to initiate the broker configuration flow.
2. Ensure you have selected a supported broker (Alpaca or MetaTrader 5).
3. If the connection fails, verify your API keys or login details are correct and have not expired.

### Signal Delivery Issues

#### Proactive Signals Not Arriving

If you are not receiving real-time signal notifications in Telegram:

1. Verify that your alerts are active. Run `/signals` in Telegram.
2. If signals are muted, run `/signals on` to turn on push notifications.
3. Check if your account subscription has expired or run out of message credits using `/usage`.
4. You can pull the latest active signals manually at any time by running `/signals`.

### Auto-Trading Execution Issues

#### Auto-Trade is Enabled but Not Executing Trades

If auto-trading is turned on using `/resume` but no trades are placed:

1. **Risk Limit Filters**: VarianTrade passes every signal through your active risk controls before sending it for execution. If a signal exceeds your maximum position size, daily drawdown, or default stop-loss constraints, the trade is blocked to protect your capital.
2. Run `/status` in Telegram to inspect your active risk configuration and drawdown metrics.
3. Check your broker's connection status. If the broker is offline, auto-trading will pause.

### AI Connection Issues

#### Remote MCP Connector Fails to Load

If your external AI editor (e.g. Cursor or Claude Desktop) cannot connect to VarianTrade:

1. Ensure the remote MCP URL is entered exactly as: `https://api.variantrades.com/mcp/rpc`.
2. Verify that your external AI application and plan support remote MCP server integrations.
3. Check your Telegram bot chat for a pending authorization prompt. You must tap **Approve** in Telegram to authorize the connection scopes.

#### Provider API Key Fails to Enroll

If your API key connection does not activate:

1. Ensure you selected **Add API key** within a private chat with the bot. Key enrollment is restricted in public or group chats for security.
2. Verify that the key has not expired and has sufficient billing balance with the provider (OpenAI, Anthropic, DeepSeek, or Gemini).
3. VarianTrade deletes the key message immediately upon receipt. If validation fails, delete the message manually if it is still visible, then restart the flow.

### CLI Companion Issues

#### Companion App is Not Executing Jobs

If the local companion (`variantrade-bridge`) is running but does not process tasks:

1. **Verify Path**: Run `variantrade-bridge providers` on your machine to check if the companion can locate your provider CLI (e.g. `claude` CLI).
2. **Authentication Status**: Ensure you are signed into the provider CLI directly on your machine. The companion does not log you in or store passwords.
3. **Verify Connection**: Run `variantrade-bridge status` to verify local enrollment status and check if the VarianTrade server is reachable.
4. **Queue Check**: The companion processes jobs one at a time. Check if a previous job is still running or has timed out.

### Contacting Support

If you cannot resolve an issue, you can open a support ticket directly from Telegram:

- Run `/complaint` in the bot chat.
- Submit a detailed description of the problem and attach any screenshots if relevant.
- Once open, the chat enters ticket routing mode, sending your messages directly to a support agent.
- Run `/close` to close the ticket after the issue is resolved.