# Introduction

**Open-source market making toolkit for AI agents and humans.**

OpenMM provides a unified interface for trading across multiple cryptocurrency exchanges, with special support for Cardano DEX aggregation via Iris Protocol.

## Features

* 🔄 **Multi-Exchange Support** — MEXC, Gate.io, Bitget, Kraken
* 📊 **REST API** — Full-featured HTTP API with OpenAPI spec
* 🤖 **MCP Server** — Model Context Protocol for AI agents
* 💹 **Grid Trading** — Automated grid strategy with volatility tracking
* 🦋 **Cardano DEX** — Pool discovery and price aggregation via Iris

## Quick Links

* [Installation](/getting-started/installation)
* [CLI Reference](/cli-reference/cli)
* [API Reference](/api-reference/overview)
* [Grid Strategy Guide](/guides/grid_strategy)

## Packages

| Package                | Description |
| ---------------------- | ----------- |
| `@3rd-eye-labs/openmm` | CLI and SDK |
| `@qbtlabs/openmm-mcp`  | MCP Server  |

## License

MIT © QBT Labs


# Installation

## NPM Package

```bash
npm install -g @3rd-eye-labs/openmm
```

## From Source

```bash
git clone https://github.com/3rd-Eye-Labs/OpenMM.git
cd OpenMM
npm install
npm run build
npm install -g .
```

## Verify Installation

```bash
openmm --version
openmm --help
```

## Exchange Setup

Run the interactive setup wizard:

```bash
openmm setup
```

This will guide you through:

1. Selecting exchanges to configure
2. Entering API credentials
3. Testing connectivity

### Manual Configuration

Create a `.env` file in your working directory:

```env
# MEXC (required)
MEXC_API_KEY=your-api-key
MEXC_SECRET=your-secret-key

# Gate.io (optional)
GATEIO_API_KEY=your-api-key
GATEIO_SECRET_KEY=your-secret-key

# Bitget (optional)
BITGET_API_KEY=your-api-key
BITGET_SECRET_KEY=your-secret-key
BITGET_PASSPHRASE=your-passphrase

# Kraken (optional)
KRAKEN_API_KEY=your-api-key
KRAKEN_SECRET_KEY=your-secret-key
```

## MCP Server

For AI agent integration:

```bash
npm install -g @qbtlabs/openmm-mcp
npx @qbtlabs/openmm-mcp setup
```

See [MCP documentation](https://github.com/QBT-Labs/openMM-MCP) for client configuration.


# Quick Start

## CLI Usage

### Check Balance

```bash
openmm balance --exchange mexc
openmm balance --exchange mexc --asset USDT
```

### Get Market Data

```bash
openmm ticker --exchange mexc --symbol BTC/USDT
openmm orderbook --exchange mexc --symbol BTC/USDT --limit 5
openmm trades --exchange mexc --symbol BTC/USDT --limit 10
```

### Place Orders

```bash
# Limit buy order
openmm order place --exchange mexc --symbol BTC/USDT --side buy --type limit --amount 0.001 --price 40000

# Market sell order
openmm order place --exchange mexc --symbol BTC/USDT --side sell --type market --amount 0.001

# List open orders
openmm order list --exchange mexc

# Cancel order
openmm order cancel --exchange mexc --orderId abc123
```

### Cardano DEX

```bash
# Get token price
openmm cardano price INDY

# Discover pools
openmm cardano pools SNEK --limit 5
```

## API Server

Start the REST API server:

```bash
openmm serve --port 3000
```

Access endpoints:

* API: `http://localhost:3000/api/v1/`
* Swagger UI: `http://localhost:3000/docs`

### Example API Calls

```bash
# Get ticker
curl "http://localhost:3000/api/v1/ticker?exchange=mexc&symbol=BTC/USDT"

# Get balance
curl "http://localhost:3000/api/v1/balance?exchange=mexc"

# Place order
curl -X POST "http://localhost:3000/api/v1/orders" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange": "mexc",
    "symbol": "BTC/USDT",
    "side": "buy",
    "type": "limit",
    "amount": 0.001,
    "price": 40000
  }'
```

## Grid Strategy

Start a grid trading strategy:

```bash
openmm grid start \
  --exchange mexc \
  --symbol BTC/USDT \
  --lower 38000 \
  --upper 42000 \
  --levels 10 \
  --size 50
```

Monitor and stop:

```bash
openmm grid status
openmm grid stop --id grid-xxx
```

See [Grid Strategy Guide](/guides/grid_strategy) for advanced configuration.


# CLI Overview

OpenMM provides a command-line interface for interacting with multiple cryptocurrency exchanges using a unified set of commands.

## Installation & Setup

### Recommended: Global Installation

```bash
# Build the project first
npm install
npm run build

# Install globally to use 'openmm' command anywhere
npm install -g .

# Now use openmm from anywhere
openmm [command] [options]
```

### Alternative: Development Mode

```bash
# Run commands during development (without global install)
npm run cli -- [command] [options]
```

### Alternative: Using npx

```bash
# Run without global installation (requires build first)
npx openmm [command] [options]
```

## Supported Exchanges

Currently supported exchanges:

* **mexc** - MEXC Exchange (fully implemented)
* **gateio** - Gate.io (fully implemented)
* **bitget** - Bitget (fully implemented)
* **kraken** - Kraken (fully implemented with WebSocket support)

## Cardano Integration

OpenMM includes comprehensive Cardano DEX integration through Iris Protocol:

* **Pool Discovery** - Find optimal liquidity pools for Cardano native tokens
* **Price Aggregation** - Get liquidity-weighted prices from multiple DEXes
* **Token Management** - Easy addition and configuration of new Cardano tokens

📖 **For token setup guide, see** [**CARDANO\_TOKENS.md**](/guides/cardano_tokens)

## Commands

### Main Help

```bash
openmm --help
```

***

## 📊 Balance Commands

Get account balance information from exchanges.

### Get All Balances

```bash
# MEXC Example
openmm balance --exchange mexc

# Gate.io Example
openmm balance --exchange gateio

# Bitget Example
openmm balance --exchange bitget

# Kraken Example
openmm balance --exchange kraken
```

### Get Specific Asset Balance

```bash
# MEXC Examples
openmm balance --exchange mexc --asset BTC
openmm balance --exchange mexc --asset USDT

# Gate.io Examples
openmm balance --exchange gateio --asset BTC
openmm balance --exchange gateio --asset USDT

# Bitget Examples
openmm balance --exchange bitget --asset BTC
openmm balance --exchange bitget --asset USDT

# Kraken Examples
openmm balance --exchange kraken --asset BTC
openmm balance --exchange kraken --asset EUR
```

### JSON Output

```bash
# MEXC Example
openmm balance --exchange mexc --json

# Bitget Example
openmm balance --exchange bitget --json

# Kraken Example
openmm balance --exchange kraken --json
```

**Options:**

* `-e, --exchange <exchange>` - Exchange to query (required)
* `-a, --asset <asset>` - Specific asset to query (optional)
* `--json` - Output in JSON format

***

## 📋 Order Commands

Manage trading orders on exchanges.

### List Open Orders

```bash
# MEXC Examples
openmm orders list --exchange mexc
openmm orders list --exchange mexc --limit 5
openmm orders list --exchange mexc --symbol BTC/USDT

# Gate.io Examples
openmm orders list --exchange gateio
openmm orders list --exchange gateio --limit 5
openmm orders list --exchange gateio --symbol BTC/USDT

# Bitget Examples
openmm orders list --exchange bitget
openmm orders list --exchange bitget --limit 5
openmm orders list --exchange bitget --symbol SNEK/USDT

# Kraken Examples
openmm orders list --exchange kraken
openmm orders list --exchange kraken --limit 5
openmm orders list --exchange kraken --symbol ADA/EUR
```

### Get Specific Order

```bash
# MEXC Example
openmm orders get --exchange mexc --id 123456 --symbol BTC/USDT

# Gate.io Example
openmm orders get --exchange gateio --id 123456 --symbol BTC/USDT

# Bitget Example
openmm orders get --exchange bitget --id 1385288398060044291 --symbol SNEK/USDT

# Kraken Example
openmm orders get --exchange kraken --id OQN3UE-LRH6U-MPLZ5I --symbol ADA/EUR
```

### Create New Order

```bash
# MEXC Examples
openmm orders create --exchange mexc --symbol BTC/USDT --side buy --type limit --amount 0.001 --price 50000
openmm orders create --exchange mexc --symbol BTC/USDT --side sell --type market --amount 0.001

# Gate.io Examples
openmm orders create --exchange gateio --symbol BTC/USDT --side buy --type limit --amount 0.001 --price 50000
openmm orders create --exchange gateio --symbol BTC/USDT --side sell --type market --amount 0.001

# Bitget Examples
openmm orders create --exchange bitget --symbol SNEK/USDT --side buy --type limit --amount 10000 --price 0.00001
openmm orders create --exchange bitget --symbol SNEK/USDT --side sell --type market --amount 5000

# Kraken Examples
openmm orders create --exchange kraken --symbol ADA/EUR --side buy --type limit --amount 50 --price 0.45
openmm orders create --exchange kraken --symbol BTC/USD --side sell --type market --amount 0.001
```

### Cancel Order

```bash
# MEXC Example
openmm orders cancel --exchange mexc --id C02__626091255599874048060 --symbol INDY/USDT

# Gate.io Example
openmm orders cancel --exchange gateio --id 123456 --symbol BTC/USDT

# Bitget Example
openmm orders cancel --exchange bitget --id 1385288398060044291 --symbol SNEK/USDT

# Kraken Example
openmm orders cancel --exchange kraken --id OQN3UE-LRH6U-MPLZ5I --symbol ADA/EUR
```

**List Options:**

* `-e, --exchange <exchange>` - Exchange to query (required)
* `-s, --symbol <symbol>` - Filter by trading pair (optional)
* `-l, --limit <limit>` - Number of orders to display (default: all)
* `--json` - Output in JSON format

**Get Options:**

* `-e, --exchange <exchange>` - Exchange to query (required)
* `-i, --id <orderId>` - Order ID (required)
* `-s, --symbol <symbol>` - Trading pair symbol (required)
* `--json` - Output in JSON format

**Create Options:**

* `-e, --exchange <exchange>` - Exchange to use (required)
* `-s, --symbol <symbol>` - Trading pair (required)
* `--side <side>` - Order side: buy/sell (required)
* `--type <type>` - Order type: market/limit (required)
* `--amount <amount>` - Order amount (required)
* `--price <price>` - Order price (required for limit orders)
* `--json` - Output in JSON format

**Cancel Options:**

* `-e, --exchange <exchange>` - Exchange to use (required)
* `-i, --id <orderId>` - Order ID to cancel (required)
* `-s, --symbol <symbol>` - Trading pair symbol (required)
* `--json` - Output in JSON format

***

## 📈 Market Data Commands

Get real-time market data from exchanges.

### Ticker Data

```bash
# MEXC Examples
openmm ticker --exchange mexc --symbol BTC/USDT
openmm ticker --exchange mexc --symbol ETH/USDT --json

# Gate.io Examples
openmm ticker --exchange gateio --symbol BTC/USDT
openmm ticker --exchange gateio --symbol ETH/USDT --json

# Bitget Examples
openmm ticker --exchange bitget --symbol SNEK/USDT
openmm ticker --exchange bitget --symbol BTC/USDT --json

# Kraken Examples
openmm ticker --exchange kraken --symbol ADA/EUR
openmm ticker --exchange kraken --symbol BTC/USD --json
```

**Options:**

* `-e, --exchange <exchange>` - Exchange to query (required)
* `-s, --symbol <symbol>` - Trading pair symbol (required)
* `--json` - Output in JSON format

### Order Book

```bash
# MEXC Examples
openmm orderbook --exchange mexc --symbol BTC/USDT
openmm orderbook --exchange mexc --symbol BTC/USDT --limit 5

# Gate.io Examples
openmm orderbook --exchange gateio --symbol BTC/USDT
openmm orderbook --exchange gateio --symbol BTC/USDT --limit 5

# Bitget Examples
openmm orderbook --exchange bitget --symbol SNEK/USDT
openmm book --exchange bitget --symbol BTC/USDT --json

# Kraken Examples
openmm orderbook --exchange kraken --symbol ADA/EUR
openmm orderbook --exchange kraken --symbol ETH/USD --limit 5 --json
```

**Options:**

* `-e, --exchange <exchange>` - Exchange to query (required)
* `-s, --symbol <symbol>` - Trading pair symbol (required)
* `-l, --limit <limit>` - Number of bid/ask levels (default: 10)
* `--json` - Output in JSON format

### Recent Trades

```bash
# MEXC Examples
openmm trades --exchange mexc --symbol BTC/USDT
openmm trades --exchange mexc --symbol BTC/USDT --limit 50
openmm trades --exchange mexc --symbol ETH/USDT --json

# Gate.io Examples
openmm trades --exchange gateio --symbol BTC/USDT
openmm trades --exchange gateio --symbol BTC/USDT --limit 50
openmm trades --exchange gateio --symbol ETH/USDT --json

# Bitget Examples
openmm trades --exchange bitget --symbol SNEK/USDT
openmm trades --exchange bitget --symbol BTC/USDT --limit 50
openmm trades --exchange bitget --symbol SNEK/USDT --json

# Kraken Examples
openmm trades --exchange kraken --symbol ADA/EUR
openmm trades --exchange kraken --symbol BTC/USD --limit 50
openmm trades --exchange kraken --symbol ETH/EUR --json
```

**Options:**

* `-e, --exchange <exchange>` - Exchange to query (required)
* `-s, --symbol <symbol>` - Trading pair symbol (required)
* `-l, --limit <limit>` - Number of trades to display (default: 20)
* `--json` - Output in JSON format

***

## 🔧 Environment Setup

### Required Configuration

Ensure your `.env` file contains the necessary API credentials:

```env
# MEXC Configuration
MEXC_API_KEY=your_mexc_api_key
MEXC_SECRET=your_mexc_secret_key

# Gate.io Configuration
GATEIO_API_KEY=your_gateio_api_key
GATEIO_SECRET=your_gateio_secret_key

# Bitget Configuration
BITGET_API_KEY=your_bitget_api_key
BITGET_SECRET=your_bitget_secret_key
BITGET_PASSPHRASE=your_bitget_passphrase  # Set when creating API key - API TOKEN

# Kraken Configuration
KRAKEN_API_KEY=your_kraken_api_key
KRAKEN_SECRET=your_kraken_secret_key

```

### Symbol Format

* Use standard format: `BTC/USDT`, `ETH/USDT`, `INDY/USDT`, `ADA/EUR`, `BTC/USD`
* The CLI automatically converts to exchange-specific format
* Kraken supports both USD/EUR fiat pairs and USDT pairs

***

## 🔍 Common Examples

### Check Balance

```bash
# MEXC - Check BTC Balance
openmm balance --exchange mexc --asset BTC

# Gate.io - Check BTC Balance
openmm balance --exchange gateio --asset BTC

# Bitget - Check USDT Balance
openmm balance --exchange bitget --asset USDT

# Kraken - Check ADA Balance
openmm balance --exchange kraken --asset ADA
```

### Get Ticker Price

```bash
# MEXC - Get ETH/USDT Price
openmm ticker --exchange mexc --symbol ETH/USDT

# Gate.io - Get BTC/USDT Price
openmm ticker --exchange gateio --symbol BTC/USDT

# Bitget - Get SNEK/USDT Price
openmm ticker --exchange bitget --symbol SNEK/USDT

# Kraken - Get ADA/EUR Price
openmm ticker --exchange kraken --symbol ADA/EUR
```

### View Order Book

```bash
# MEXC - BTC/USDT Order Book
openmm orderbook --exchange mexc --symbol BTC/USDT --limit 5

# Gate.io - BTC/USDT Order Book
openmm orderbook --exchange gateio --symbol BTC/USDT --limit 5

# Bitget - SNEK/USDT Order Book
openmm orderbook --exchange bitget --symbol SNEK/USDT --limit 10

# Kraken - ADA/EUR Order Book
openmm orderbook --exchange kraken --symbol ADA/EUR --limit 5
```

### Place Orders

```bash
# MEXC - Limit Buy Order
openmm orders create --exchange mexc --symbol BTC/USDT --side buy --type limit --amount 0.001 --price 45000

# Gate.io - Limit Buy Order
openmm orders create --exchange gateio --symbol BTC/USDT --side buy --type limit --amount 0.001 --price 45000

# Bitget - Limit Buy Order
openmm orders create --exchange bitget --symbol SNEK/USDT --side buy --type limit --amount 10000 --price 0.00001

# Kraken - Limit Buy Order  
openmm orders create --exchange kraken --symbol ADA/EUR --side buy --type limit --amount 50 --price 0.45
```

### List Open Orders

```bash
# MEXC - All Open Orders
openmm orders list --exchange mexc

# Gate.io - All Open Orders
openmm orders list --exchange gateio

# Bitget - Open Orders for SNEK/USDT
openmm orders list --exchange bitget --symbol SNEK/USDT

# Kraken - Open Orders for ADA/EUR
openmm orders list --exchange kraken --symbol ADA/EUR
```

***

## 🏊 Cardano Pool Discovery Commands

Discover and analyze Cardano DEX liquidity pools for native tokens.

### Discover Pools for a Token

```bash
# Discover pools for NIGHT token
openmm pool-discovery discover NIGHT

# Discover top 5 pools for SNEK token
openmm pool-discovery discover SNEK --limit 5

# Find pools with minimum $50K liquidity for INDY
openmm pool-discovery discover INDY --min-liquidity 50000

# Show all available pools for a token
openmm pool-discovery discover INDY --show-all
```

### List Supported Tokens

```bash
# See all supported Cardano tokens
openmm pool-discovery supported
```

### Get Live Pool Prices

```bash
openmm pool-discovery prices NIGHT
```

**Pool Discovery Options:**

* `--limit <number>` - Limit number of pools shown (default: 10)
* `--min-liquidity <number>` - Filter pools by minimum TVL in dollars
* `--show-all` - Show all pools (ignore limit)

**Supported Cardano Tokens:**

* **NIGHT** - Midnight
* **SNEK** - Snek Token
* **INDY** - Indigo Protocol

***

## 📊 Price Comparison Commands

Compare token prices across multiple exchanges (MEXC, Gate.io, Bitget) and Cardano DEX pools.

### Compare Prices Across All Sources

```bash
# Compare SNEK across DEX and CEX
openmm price-comparison --symbol SNEK

# Compare INDY prices
openmm price-comparison --symbol INDY
```

***

## 📖 Help

Get help for any command:

```bash
openmm --help                    # Main help
openmm balance --help            # Balance command help  
openmm orders --help             # Orders command help
openmm orders create --help      # Order creation help
openmm ticker --help             # Ticker command help
openmm orderbook --help          # Order book command help
openmm trades --help             # Trades command help
openmm pool-discovery --help     # Pool discovery help
openmm price-comparison --help   # Price comparison help
```

***


# Trading Strategies

## Overview

This document outlines the comprehensive trading strategies that can be implemented using the OpenMM SDK's multi-exchange architecture. These strategies are designed to leverage the unified interface across MEXC, Gate.io, Bitget, and Kraken exchanges for maximum trading opportunities in the Cardano ecosystem.

## Strategy Categories

### 1. Arbitrage Strategies

#### 1.1 Cross-Exchange Arbitrage

**Concept**: Exploit price differences across multiple exchanges simultaneously.

**Implementation Details**:

* Monitor real-time price feeds from all 4 exchanges
* Calculate spread differences accounting for fees and slippage
* Execute buy/sell orders when spread exceeds threshold (0.5-1.0%)
* Handle position rebalancing across exchanges

**Technical Requirements**:

* Sub-second latency WebSocket connections
* Concurrent order execution capability
* Real-time balance monitoring across all exchanges

**Risk Management**:

* Maximum position size per exchange
* Minimum profit threshold accounting for fees
* Transfer time considerations between exchanges
* Circuit breakers for unusual market conditions

```typescript
interface ArbitrageConfig {
  minSpreadThreshold: number;      // 0.005 (0.5%)
  maxPositionSize: number;         // Per exchange limit
  exchanges: ExchangeId[];         // ['mexc', 'gateio', 'bitget', 'kraken']
  feeAdjustment: number;          // Total fee cost consideration
}
```

#### 1.2 Triangular Arbitrage

**Concept**: Exploit price inefficiencies in triangular trading pairs (ADA/USDT, ADA/BTC, BTC/USDT).

**Implementation**:

* Monitor all three pairs across multiple exchanges
* Calculate triangular arbitrage opportunities
* Execute three-leg trades for profit extraction
* Use different exchanges for optimal execution per leg

**Multi-Exchange Advantage**:

* Higher probability of profitable opportunities
* Better liquidity distribution
* Reduced execution risk

### 2. Enhanced Grid Strategies

#### 2.1 Multi-Exchange Grid Trading

**Evolution**: Extension of current single-exchange grid strategy.

**Features**:

* Coordinated grid placement across multiple exchanges
* Dynamic exchange selection based on liquidity
* Cross-exchange inventory management
* Unified profit tracking

**Benefits**:

* Increased total liquidity access
* Reduced single-exchange dependency risk
* Better price discovery and execution

```typescript
interface MultiExchangeGridConfig extends GridConfig {
  exchangeWeights: Record<ExchangeId, number>;  // Distribution weights
  rebalanceThreshold: number;                   // When to rebalance between exchanges
  preferredExchange: ExchangeId;               // Primary execution exchange
}
```

#### 2.2 Volatility-Adaptive Grid

**Enhancement**: Dynamic grid spacing based on market volatility.

**Implementation**:

* Calculate real-time volatility metrics (ATR, Standard Deviation)
* Adjust grid spacing automatically based on market conditions
* Wider spreads in high volatility, tighter in low volatility
* Multi-exchange volatility aggregation for better signals

**Milestone 3 Features**:

* 20-level grid capability (10 buy, 10 sell)
* Dynamic spread adjustment based on volatility indicators
* Per-exchange volatility customization

### 3. Market Making Strategies

#### 3.1 Cross-Exchange Market Making

**Concept**: Provide liquidity simultaneously across all supported exchanges.

**Strategy Components**:

* Unified order book aggregation
* Dynamic spread calculation per exchange
* Inventory risk management across exchanges
* Profit optimization through exchange selection

**Implementation**:

* Monitor order book depth on all exchanges
* Adjust bid/ask spreads based on competition
* Maintain target inventory levels per exchange
* Automatic rebalancing when limits exceeded

#### 3.2 Lead-Lag Market Making

**Advanced Strategy**: Use price movements on major exchanges to predict minor exchange movements.

**Methodology**:

* Identify lead exchanges (typically MEXC/Kraken for volume)
* Monitor price movements and order flow
* Predict movements on follower exchanges (Gate.io/Bitget)
* Position orders anticipating price convergence

**Risk Controls**:

* Maximum lag time thresholds
* Position size limits per prediction
* Stop-loss mechanisms for failed predictions

### 4. Momentum & Mean Reversion Strategies

#### 4.1 Multi-Exchange Momentum Trading

**Signal Generation**: Aggregate momentum indicators across all exchanges.

**Components**:

* Volume-weighted price momentum
* Cross-exchange momentum confirmation
* Breakout detection with multi-exchange validation
* Trend following with dynamic position sizing

**Execution Strategy**:

* Trade on exchange with best liquidity/spreads
* Use secondary exchanges for hedging
* Dynamic position scaling based on momentum strength

#### 4.2 Statistical Arbitrage

**Concept**: Trade based on historical price relationships between exchanges.

**Implementation**:

* Calculate historical price correlations between exchanges
* Identify mean-reverting relationships
* Generate Z-scores for price ratio deviations
* Execute trades betting on convergence to historical mean

**Risk Management**:

* Maximum drawdown limits
* Position sizing based on confidence intervals
* Stop-loss based on statistical significance

### 5. Advanced Order Strategies

#### 5.1 TWAP (Time-Weighted Average Price)

**Use Case**: Execute large orders with minimal market impact.

**Strategy**:

* Split large orders into smaller chunks
* Distribute execution across time and exchanges
* Monitor market impact and adjust execution speed
* Optimize for best average execution price

**Multi-Exchange Benefits**:

* Larger total liquidity pool
* Reduced per-exchange market impact
* Better price improvement opportunities

#### 5.2 Smart Order Routing

**Real-Time Optimization**: Route each order to optimal exchange at execution time.

**Decision Factors**:

* Current bid/ask spreads
* Available liquidity depth
* Exchange fees and rebates
* Network latency considerations

**Implementation**:

* Real-time exchange scoring algorithm
* Dynamic routing decisions per order
* Execution quality monitoring and feedback

```typescript
interface SmartRoutingConfig {
  factors: {
    spread: number;           // Weight for bid-ask spread
    liquidity: number;        // Weight for available liquidity  
    fees: number;            // Weight for fee considerations
    latency: number;         // Weight for execution speed
  };
  fallbackExchange: ExchangeId;  // If primary routing fails
  maxLatency: number;           // Maximum acceptable latency
}
```

### 6. Risk Management Strategies

#### 6.1 Portfolio Hedging

**Multi-Exchange Risk Control**: Manage portfolio risk across all exchanges.

**Components**:

* Cross-exchange position correlation analysis
* Dynamic hedging based on portfolio exposure
* Risk limit enforcement per exchange and globally
* Automatic rebalancing triggers

**Hedging Mechanisms**:

* Long/short position balancing
* Cross-asset hedging (ADA vs other tokens)
* Volatility hedging using options (where available)

#### 6.2 Liquidity Provision with Inventory Control

**Sophisticated Market Making**: Balance liquidity provision with inventory risk.

**Features**:

* Target inventory ratios per exchange
* Dynamic spread adjustment based on inventory levels
* Automatic position flattening at risk limits
* Cross-exchange inventory transfers

### 7. Data-Driven Strategies

#### 7.1 Order Book Imbalance Trading

**Signal**: Detect and trade on order book imbalances across exchanges.

**Analysis**:

* Real-time order book depth analysis
* Imbalance ratio calculations
* Predictive modeling for price movements
* Cross-exchange imbalance arbitrage

**Execution**:

* Trade direction based on imbalance signals
* Position sizing based on imbalance magnitude
* Quick execution to capture price movements

#### 7.2 Volume Profile Analysis

**Multi-Exchange Volume Intelligence**: Use aggregated volume data for trading decisions.

**Components**:

* Volume-at-price analysis across all exchanges
* Support/resistance level identification
* Breakout confirmation with volume
* Volume-based position sizing

## Implementation Roadmap

### Milestone 2: Multi-Exchange Integration & Price Aggregation

#### Priority 1 Strategies:

1. **Cross-Exchange Arbitrage**
   * Direct benefit from real-time price aggregation
   * Foundation for multi-exchange trading
   * Revenue generation to fund further development
2. **Enhanced Multi-Exchange Grid**
   * Evolution of proven grid strategy
   * Leverage existing codebase
   * Demonstrate multi-exchange coordination
3. **Smart Order Routing**
   * Showcase unified trading interface
   * Immediate user experience improvement
   * Foundation for advanced strategies

#### Technical Implementation:

```typescript
// Enhanced strategy base class for multi-exchange
abstract class MultiExchangeStrategy extends BaseStrategy {
  protected exchanges: Map<ExchangeId, BaseExchangeConnector>;
  protected priceAggregator: PriceAggregationService;
  
  abstract executeAcrossExchanges(): Promise<void>;
  abstract handleCrossExchangeEvent(event: CrossExchangeEvent): Promise<void>;
}
```

### Milestone 3: Kraken Integration & Advanced Features

#### Priority 1 Strategies:

1. **Advanced Market Making**
   * 20-level dynamic order placement
   * Sophisticated inventory management
   * Professional market maker features
2. **Statistical Arbitrage**
   * Leverage complete 4-exchange historical data
   * Machine learning price prediction models
   * Quantitative trading capabilities
3. **TWAP & Portfolio Strategies**
   * Institutional-grade order execution
   * CLI tools for strategy management
   * Advanced portfolio optimization

#### Advanced Features:

* **Dynamic Order Level Generation**: 20-level capability with configurable pricing
* **CLI Strategy Management**: Complete workflow for strategy configuration and monitoring
* **Enhanced Grid with Volatility Adaptation**: Real-time spread adjustment
* **Multi-Exchange Risk Management**: Unified risk controls across all exchanges

### CLI Integration for Advanced Strategies

#### Strategy Configuration Commands:

```bash
# Configure multi-exchange arbitrage
openmm strategy create arbitrage --exchanges mexc,gateio,bitget,kraken --min-spread 0.005

# Setup 20-level grid with volatility adaptation
openmm strategy create grid --levels 20 --volatility-adaptive --exchanges all

# Monitor strategy performance
openmm strategy monitor --strategy-id grid-001 --metrics pnl,volume,trades

# Rebalance positions across exchanges
openmm portfolio rebalance --target-ratio 25,25,25,25 --exchanges mexc,gateio,bitget,kraken
```

#### Real-Time Monitoring:

```bash
# Live strategy dashboard
openmm dashboard --strategies all --exchanges all

# Risk monitoring
openmm risk monitor --max-drawdown 5% --position-limits exchange:1000,global:3000

# Performance analytics
openmm analytics generate --period 7d --strategies arbitrage,grid --format html
```

## Strategy Performance Metrics

### Key Performance Indicators (KPIs):

1. **Sharpe Ratio**: Risk-adjusted returns
2. **Maximum Drawdown**: Worst-case scenario analysis
3. **Win Rate**: Percentage of profitable trades
4. **Profit Factor**: Gross profit / gross loss ratio
5. **Average Trade Duration**: Strategy efficiency metric
6. **Capital Utilization**: Effective use of available capital

### Multi-Exchange Specific Metrics:

1. **Cross-Exchange Correlation**: Portfolio diversification measure
2. **Exchange Performance Ratio**: Individual exchange contribution
3. **Arbitrage Capture Rate**: Percentage of identified opportunities executed
4. **Latency Impact**: Execution speed effect on profitability
5. **Inventory Turnover**: Capital efficiency across exchanges

## Risk Considerations

### Technical Risks:

* **Latency Risk**: Network delays affecting arbitrage opportunities
* **Exchange Connectivity**: Redundancy and failover mechanisms
* **Order Execution Risk**: Partial fills and slippage across exchanges
* **API Rate Limits**: Exchange-specific limitations

### Market Risks:

* **Correlation Risk**: Simultaneous adverse moves across exchanges
* **Liquidity Risk**: Reduced liquidity during market stress
* **Counter-party Risk**: Exchange-specific operational risks
* **Regulatory Risk**: Changing regulations affecting exchange operations

### Operational Risks:

* **Position Tracking**: Accurate inventory management across exchanges
* **Settlement Risk**: Transfer delays between exchanges
* **Technology Risk**: System failures and recovery procedures
* **Capital Risk**: Adequate capital allocation and management

## Future Strategy Enhancements

### Machine Learning Integration:

* **Predictive Models**: Price movement prediction using multi-exchange data
* **Pattern Recognition**: Automated trading pattern identification
* **Reinforcement Learning**: Self-improving trading strategies
* **Sentiment Analysis**: News and social media impact on trading

### Advanced Analytics:

* **Real-Time Strategy Optimization**: Dynamic parameter adjustment
* **Multi-Asset Strategies**: Expand beyond ADA to other Cardano tokens
* **Cross-Chain Opportunities**: Bridge arbitrage with other blockchains
* **Derivatives Integration**: Options and futures strategies where available

This comprehensive strategy framework provides a clear roadmap for implementing sophisticated trading strategies that fully leverage the OpenMM SDK's multi-exchange architecture and advanced features planned for Milestones 2-3.


# API Overview

OpenMM provides a REST API built with Fastify, featuring automatic OpenAPI documentation.

## Base URL

```
http://localhost:3000/api/v1
```

## Starting the Server

```bash
openmm serve --port 3000
```

Options:

* `--port` — Port number (default: 3000)
* `--host` — Host address (default: 0.0.0.0)

## Interactive Documentation

Swagger UI is available at:

```
http://localhost:3000/docs
```

## Response Format

All responses are JSON with consistent structure:

### Success Response

```json
{
  "exchange": "mexc",
  "symbol": "BTC/USDT",
  "data": { ... },
  "timestamp": 1710000000000
}
```

### Error Response

```json
{
  "error": "Error message here"
}
```

## HTTP Status Codes

| Code | Description                        |
| ---- | ---------------------------------- |
| 200  | Success                            |
| 400  | Bad Request — Invalid parameters   |
| 404  | Not Found — Resource doesn't exist |
| 500  | Server Error — Internal error      |

## Endpoints Summary

### Market Data

| Method | Endpoint   | Description                 |
| ------ | ---------- | --------------------------- |
| GET    | /ticker    | Get ticker for trading pair |
| GET    | /orderbook | Get order book              |
| GET    | /trades    | Get recent trades           |

### Account

| Method | Endpoint | Description          |
| ------ | -------- | -------------------- |
| GET    | /balance | Get account balances |

### Orders

| Method | Endpoint    | Description       |
| ------ | ----------- | ----------------- |
| GET    | /orders     | List open orders  |
| GET    | /orders/:id | Get order by ID   |
| POST   | /orders     | Create new order  |
| DELETE | /orders/:id | Cancel order      |
| DELETE | /orders     | Cancel all orders |

### Strategy

| Method | Endpoint              | Description            |
| ------ | --------------------- | ---------------------- |
| POST   | /strategy/grid        | Start grid strategy    |
| DELETE | /strategy/grid        | Stop grid strategy     |
| GET    | /strategy/grid/status | Get strategy status    |
| GET    | /strategy/grid/list   | List active strategies |

### Cardano DEX

| Method | Endpoint               | Description              |
| ------ | ---------------------- | ------------------------ |
| GET    | /cardano/price/:symbol | Get token price          |
| GET    | /cardano/pools/:symbol | Discover liquidity pools |

### Price Comparison

| Method | Endpoint       | Description                     |
| ------ | -------------- | ------------------------------- |
| GET    | /price/compare | Compare prices across exchanges |

## Supported Exchanges

| ID     | Name    | Status         |
| ------ | ------- | -------------- |
| mexc   | MEXC    | ✅ Full support |
| gateio | Gate.io | ✅ Full support |
| bitget | Bitget  | ✅ Full support |
| kraken | Kraken  | ✅ Full support |


# Authentication

The OpenMM API server uses environment-based authentication. API credentials are configured server-side, not passed in requests.

## Server Configuration

Before starting the API server, configure exchange credentials in your environment:

```bash
# .env file
MEXC_API_KEY=your-api-key
MEXC_SECRET=your-secret-key

GATEIO_API_KEY=your-api-key
GATEIO_SECRET_KEY=your-secret-key

BITGET_API_KEY=your-api-key
BITGET_SECRET_KEY=your-secret-key
BITGET_PASSPHRASE=your-passphrase

KRAKEN_API_KEY=your-api-key
KRAKEN_SECRET_KEY=your-secret-key
```

## Security Considerations

### Local Development

The API server is designed for local use or trusted network environments.

### Production Deployment

For production deployments, consider:

1. **Reverse Proxy** — Use nginx/caddy with TLS termination
2. **API Gateway** — Add authentication layer (JWT, API keys)
3. **Network Isolation** — Run on private network only
4. **Rate Limiting** — Implement request throttling

### Example: Basic Auth with nginx

```nginx
location /api/ {
    auth_basic "OpenMM API";
    auth_basic_user_file /etc/nginx/.htpasswd;
    proxy_pass http://localhost:3000;
}
```

## Request Headers

No special headers required for local use.

For future x402 micropayment support:

```
X-402-Payment: <payment-token>
```


# Market Data

Real-time market data endpoints for supported exchanges.

## Endpoints

| Method | Endpoint                                           | Description                 |
| ------ | -------------------------------------------------- | --------------------------- |
| GET    | [/ticker](/api-reference/market-data/ticker)       | Get ticker for trading pair |
| GET    | [/orderbook](/api-reference/market-data/orderbook) | Get order book (bids/asks)  |
| GET    | [/trades](/api-reference/market-data/trades)       | Get recent trades           |

## Common Parameters

All market data endpoints require:

| Parameter | Type   | Required | Description                                       |
| --------- | ------ | -------- | ------------------------------------------------- |
| exchange  | string | ✅        | Exchange ID: `mexc`, `gateio`, `bitget`, `kraken` |
| symbol    | string | ✅        | Trading pair in `BASE/QUOTE` format               |

## Example

```bash
curl "http://localhost:3000/api/v1/ticker?exchange=mexc&symbol=BTC/USDT"
```

## Trading Pairs

Use standard format: `BASE/QUOTE`

Examples:

* `BTC/USDT`
* `ETH/USDT`
* `ADA/EUR` (Kraken)
* `INDY/ADA` (Cardano via Iris)


# GET /ticker

Get current ticker data for a trading pair.

## Request

```
GET /api/v1/ticker?exchange={exchange}&symbol={symbol}
```

### Parameters

| Parameter | Type   | Required | Description                   |
| --------- | ------ | -------- | ----------------------------- |
| exchange  | string | ✅        | Exchange ID                   |
| symbol    | string | ✅        | Trading pair (e.g., BTC/USDT) |

## Response

```json
{
  "exchange": "mexc",
  "symbol": "BTC/USDT",
  "last": 42150.50,
  "bid": 42148.00,
  "ask": 42152.00,
  "spread": 4.00,
  "spreadPercent": 0.0095,
  "baseVolume": 1234.56,
  "quoteVolume": 52000000.00,
  "timestamp": 1710000000000
}
```

### Response Fields

| Field         | Type   | Description                  |
| ------------- | ------ | ---------------------------- |
| last          | number | Last traded price            |
| bid           | number | Best bid price               |
| ask           | number | Best ask price               |
| spread        | number | Absolute spread (ask - bid)  |
| spreadPercent | number | Spread as % of mid price     |
| baseVolume    | number | 24h volume in base currency  |
| quoteVolume   | number | 24h volume in quote currency |
| timestamp     | number | Data timestamp (ms)          |

## Examples

### cURL

```bash
curl "http://localhost:3000/api/v1/ticker?exchange=mexc&symbol=BTC/USDT"
```

### JavaScript

```javascript
const response = await fetch(
  'http://localhost:3000/api/v1/ticker?exchange=mexc&symbol=BTC/USDT'
);
const ticker = await response.json();
console.log(`BTC price: $${ticker.last}`);
```

## Errors

| Code | Error            | Description                   |
| ---- | ---------------- | ----------------------------- |
| 400  | Invalid exchange | Exchange not supported        |
| 400  | Missing symbol   | Symbol parameter required     |
| 500  | Exchange error   | Failed to fetch from exchange |


# GET /orderbook

Get the order book (bids and asks) for a trading pair.

## Request

```
GET /api/v1/orderbook?exchange={exchange}&symbol={symbol}&limit={limit}
```

### Parameters

| Parameter | Type   | Required | Default | Description              |
| --------- | ------ | -------- | ------- | ------------------------ |
| exchange  | string | ✅        | —       | Exchange ID              |
| symbol    | string | ✅        | —       | Trading pair             |
| limit     | number | ❌        | 10      | Number of levels (1-100) |

## Response

```json
{
  "exchange": "mexc",
  "symbol": "BTC/USDT",
  "bids": [
    { "price": 42148.00, "amount": 0.5, "total": 0.5 },
    { "price": 42145.00, "amount": 1.2, "total": 1.7 },
    { "price": 42140.00, "amount": 0.8, "total": 2.5 }
  ],
  "asks": [
    { "price": 42152.00, "amount": 0.3, "total": 0.3 },
    { "price": 42155.00, "amount": 0.7, "total": 1.0 },
    { "price": 42160.00, "amount": 1.5, "total": 2.5 }
  ],
  "spread": 4.00,
  "spreadPercent": 0.0095,
  "timestamp": 1710000000000
}
```

### Response Fields

| Field         | Type   | Description                   |
| ------------- | ------ | ----------------------------- |
| bids          | array  | Buy orders (price descending) |
| asks          | array  | Sell orders (price ascending) |
| spread        | number | Best ask - best bid           |
| spreadPercent | number | Spread as % of mid price      |

Each order level contains:

* `price` — Price level
* `amount` — Size at this level
* `total` — Cumulative size

## Examples

```bash
# Get top 20 levels
curl "http://localhost:3000/api/v1/orderbook?exchange=mexc&symbol=BTC/USDT&limit=20"
```

## Errors

| Code | Error          | Description                |
| ---- | -------------- | -------------------------- |
| 400  | Invalid limit  | Limit must be 1-100        |
| 500  | Exchange error | Failed to fetch order book |


# GET /trades

Get recent trades for a trading pair.

## Request

```
GET /api/v1/trades?exchange={exchange}&symbol={symbol}&limit={limit}
```

### Parameters

| Parameter | Type   | Required | Default | Description              |
| --------- | ------ | -------- | ------- | ------------------------ |
| exchange  | string | ✅        | —       | Exchange ID              |
| symbol    | string | ✅        | —       | Trading pair             |
| limit     | number | ❌        | 50      | Number of trades (1-500) |

## Response

```json
{
  "exchange": "mexc",
  "symbol": "BTC/USDT",
  "trades": [
    {
      "id": "123456",
      "price": 42150.50,
      "amount": 0.15,
      "side": "buy",
      "timestamp": 1710000000000
    }
  ],
  "summary": {
    "count": 50,
    "buyCount": 28,
    "sellCount": 22,
    "buyVolume": 12.5,
    "sellVolume": 9.8,
    "avgPrice": 42148.25,
    "vwap": 42147.80
  },
  "timestamp": 1710000000000
}
```

### Summary Fields

| Field      | Type   | Description                   |
| ---------- | ------ | ----------------------------- |
| count      | number | Total trades                  |
| buyCount   | number | Buy trades count              |
| sellCount  | number | Sell trades count             |
| buyVolume  | number | Total buy volume              |
| sellVolume | number | Total sell volume             |
| avgPrice   | number | Simple average price          |
| vwap       | number | Volume-weighted average price |

## Examples

```bash
curl "http://localhost:3000/api/v1/trades?exchange=mexc&symbol=BTC/USDT&limit=100"
```


# Account

Account-related endpoints for balance and portfolio information.

## Endpoints

| Method | Endpoint                                   | Description          |
| ------ | ------------------------------------------ | -------------------- |
| GET    | [/balance](/api-reference/account/balance) | Get account balances |

## Authentication

Account endpoints require valid exchange credentials configured on the server.


# GET /balance

Get account balances for an exchange.

## Request

```
GET /api/v1/balance?exchange={exchange}&asset={asset}
```

### Parameters

| Parameter | Type   | Required | Description                       |
| --------- | ------ | -------- | --------------------------------- |
| exchange  | string | ✅        | Exchange ID                       |
| asset     | string | ❌        | Filter by asset (e.g., BTC, USDT) |

## Response

```json
{
  "exchange": "mexc",
  "balances": [
    {
      "asset": "USDT",
      "free": "10000.00",
      "used": "500.00",
      "total": "10500.00"
    },
    {
      "asset": "BTC",
      "free": "0.5",
      "used": "0.1",
      "total": "0.6"
    }
  ],
  "timestamp": 1710000000000
}
```

### Balance Fields

| Field | Type   | Description       |
| ----- | ------ | ----------------- |
| asset | string | Asset symbol      |
| free  | string | Available balance |
| used  | string | In orders/locked  |
| total | string | free + used       |

## Examples

```bash
# All balances (non-zero)
curl "http://localhost:3000/api/v1/balance?exchange=mexc"

# Specific asset
curl "http://localhost:3000/api/v1/balance?exchange=mexc&asset=BTC"
```

## Notes

* Zero balances are filtered out by default
* When filtering by asset, zero balances are included


# Orders

Order management endpoints for listing, creating, and canceling orders.

## Endpoints

| Method | Endpoint                                           | Description       |
| ------ | -------------------------------------------------- | ----------------- |
| GET    | [/orders](/api-reference/orders/orders-list)       | List open orders  |
| GET    | [/orders/:id](/api-reference/orders/orders-get)    | Get order by ID   |
| POST   | [/orders](/api-reference/orders/orders-create)     | Create new order  |
| DELETE | [/orders/:id](/api-reference/orders/orders-cancel) | Cancel order      |
| DELETE | [/orders](/api-reference/orders/orders-cancel-all) | Cancel all orders |

## Order Types

| Type   | Description                   |
| ------ | ----------------------------- |
| limit  | Order at specific price       |
| market | Order at current market price |

## Order Sides

| Side | Description      |
| ---- | ---------------- |
| buy  | Buy/long order   |
| sell | Sell/short order |

## Order Status

| Status            | Description              |
| ----------------- | ------------------------ |
| open              | Order is active          |
| filled            | Order fully executed     |
| partially\_filled | Order partially executed |
| canceled          | Order was canceled       |


# GET /orders

List open orders on an exchange.

## Request

```
GET /api/v1/orders?exchange={exchange}&symbol={symbol}
```

### Parameters

| Parameter | Type   | Required | Description            |
| --------- | ------ | -------- | ---------------------- |
| exchange  | string | ✅        | Exchange ID            |
| symbol    | string | ❌        | Filter by trading pair |

## Response

```json
{
  "exchange": "mexc",
  "orders": [
    {
      "id": "123456",
      "symbol": "BTC/USDT",
      "side": "buy",
      "type": "limit",
      "price": 40000,
      "amount": 0.1,
      "filled": 0,
      "remaining": 0.1,
      "status": "open",
      "timestamp": 1710000000000
    }
  ],
  "count": 1
}
```

## Examples

```bash
# All open orders
curl "http://localhost:3000/api/v1/orders?exchange=mexc"

# Filter by symbol
curl "http://localhost:3000/api/v1/orders?exchange=mexc&symbol=BTC/USDT"
```


# GET /orders/:id

Get details of a specific order.

## Request

```
GET /api/v1/orders/{id}?exchange={exchange}&symbol={symbol}
```

### Parameters

| Parameter | Type   | Required | Description     |
| --------- | ------ | -------- | --------------- |
| id        | string | ✅        | Order ID (path) |
| exchange  | string | ✅        | Exchange ID     |
| symbol    | string | ✅        | Trading pair    |

## Response

```json
{
  "exchange": "mexc",
  "order": {
    "id": "123456",
    "symbol": "BTC/USDT",
    "side": "buy",
    "type": "limit",
    "price": 40000,
    "amount": 0.1,
    "filled": 0.05,
    "remaining": 0.05,
    "status": "partially_filled",
    "timestamp": 1710000000000
  }
}
```

## Errors

| Code | Error           | Description            |
| ---- | --------------- | ---------------------- |
| 404  | Order not found | Order ID doesn't exist |


# POST /orders

Create a new order.

## Request

```
POST /api/v1/orders
Content-Type: application/json
```

### Body

```json
{
  "exchange": "mexc",
  "symbol": "BTC/USDT",
  "side": "buy",
  "type": "limit",
  "amount": 0.1,
  "price": 40000
}
```

### Parameters

| Parameter | Type   | Required | Description                 |
| --------- | ------ | -------- | --------------------------- |
| exchange  | string | ✅        | Exchange ID                 |
| symbol    | string | ✅        | Trading pair                |
| side      | string | ✅        | `buy` or `sell`             |
| type      | string | ✅        | `limit` or `market`         |
| amount    | number | ✅        | Order size in base currency |
| price     | number | ⚠️       | Required for limit orders   |

## Response

```json
{
  "success": true,
  "exchange": "mexc",
  "order": {
    "id": "123456",
    "symbol": "BTC/USDT",
    "side": "buy",
    "type": "limit",
    "price": 40000,
    "amount": 0.1,
    "filled": 0,
    "remaining": 0.1,
    "status": "open",
    "timestamp": 1710000000000
  }
}
```

## Examples

### Limit Order

```bash
curl -X POST "http://localhost:3000/api/v1/orders" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange": "mexc",
    "symbol": "BTC/USDT",
    "side": "buy",
    "type": "limit",
    "amount": 0.1,
    "price": 40000
  }'
```

### Market Order

```bash
curl -X POST "http://localhost:3000/api/v1/orders" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange": "mexc",
    "symbol": "BTC/USDT",
    "side": "sell",
    "type": "market",
    "amount": 0.1
  }'
```

## Errors

| Code | Error          | Description                  |
| ---- | -------------- | ---------------------------- |
| 400  | Invalid side   | Side must be buy or sell     |
| 400  | Invalid type   | Type must be limit or market |
| 400  | Price required | Limit orders need price      |
| 500  | Order failed   | Exchange rejected order      |


# DELETE /orders/:id

Cancel a specific order.

## Request

```
DELETE /api/v1/orders/{id}?exchange={exchange}&symbol={symbol}
```

### Parameters

| Parameter | Type   | Required | Description     |
| --------- | ------ | -------- | --------------- |
| id        | string | ✅        | Order ID (path) |
| exchange  | string | ✅        | Exchange ID     |
| symbol    | string | ✅        | Trading pair    |

## Response

```json
{
  "success": true,
  "exchange": "mexc",
  "orderId": "123456",
  "message": "Order cancelled successfully"
}
```

## Examples

```bash
curl -X DELETE "http://localhost:3000/api/v1/orders/123456?exchange=mexc&symbol=BTC/USDT"
```

## Errors

| Code | Error           | Description                    |
| ---- | --------------- | ------------------------------ |
| 404  | Order not found | Order doesn't exist            |
| 500  | Cancel failed   | Exchange rejected cancellation |


# DELETE /orders

Cancel all open orders on an exchange.

## Request

```
DELETE /api/v1/orders?exchange={exchange}&symbol={symbol}
```

### Parameters

| Parameter | Type   | Required | Description            |
| --------- | ------ | -------- | ---------------------- |
| exchange  | string | ✅        | Exchange ID            |
| symbol    | string | ❌        | Filter by trading pair |

## Response

```json
{
  "success": true,
  "exchange": "mexc",
  "cancelled": 5,
  "message": "Cancelled 5 orders"
}
```

## Examples

```bash
# Cancel all orders
curl -X DELETE "http://localhost:3000/api/v1/orders?exchange=mexc"

# Cancel orders for specific pair
curl -X DELETE "http://localhost:3000/api/v1/orders?exchange=mexc&symbol=BTC/USDT"
```

## ⚠️ Warning

This operation cancels all matching orders immediately. Use with caution.


# Strategy

Grid trading strategy management endpoints.

## Endpoints

| Method | Endpoint                                                              | Description            |
| ------ | --------------------------------------------------------------------- | ---------------------- |
| POST   | [/strategy/grid](/api-reference/strategy/strategy-grid-start)         | Start grid strategy    |
| DELETE | [/strategy/grid](/api-reference/strategy/strategy-grid-stop)          | Stop grid strategy     |
| GET    | [/strategy/grid/status](/api-reference/strategy/strategy-grid-status) | Get strategy status    |
| GET    | /strategy/grid/list                                                   | List active strategies |

## What is Grid Trading?

Grid trading places buy and sell orders at regular price intervals (the "grid"). When price moves up, sell orders execute. When price moves down, buy orders execute. This captures profit from price oscillation.

## Grid Parameters

| Parameter  | Description                                   |
| ---------- | --------------------------------------------- |
| lowerPrice | Bottom of the grid range                      |
| upperPrice | Top of the grid range                         |
| gridLevels | Number of grid lines (more = tighter spacing) |
| orderSize  | Size per order in quote currency              |

## Example Setup

A grid from $40,000 to $44,000 with 10 levels creates orders every $400:

* Buy orders: $40,000, $40,400, $40,800, ...
* Sell orders: $42,800, $43,200, $43,600, $44,000

See [Grid Strategy Guide](/guides/grid_strategy) for advanced configuration.


# POST /strategy/grid

Start a new grid trading strategy.

## Request

```
POST /api/v1/strategy/grid
Content-Type: application/json
```

### Body

```json
{
  "exchange": "mexc",
  "symbol": "BTC/USDT",
  "lowerPrice": 40000,
  "upperPrice": 44000,
  "gridLevels": 10,
  "orderSize": 100
}
```

### Parameters

| Parameter   | Type   | Required | Description                                 |
| ----------- | ------ | -------- | ------------------------------------------- |
| exchange    | string | ✅        | Exchange ID                                 |
| symbol      | string | ✅        | Trading pair                                |
| lowerPrice  | number | ✅        | Lower price bound                           |
| upperPrice  | number | ✅        | Upper price bound                           |
| gridLevels  | number | ✅        | Number of grid levels (2-100)               |
| orderSize   | number | ✅        | Size per order in quote currency            |
| gridSpacing | number | ❌        | Custom spacing (auto-calculated if omitted) |

## Response

```json
{
  "id": "grid-mexc-BTC-USDT-1710000000000",
  "status": "running",
  "message": "Grid strategy started successfully",
  "config": {
    "exchange": "mexc",
    "symbol": "BTC/USDT",
    "lowerPrice": 40000,
    "upperPrice": 44000,
    "gridLevels": 10,
    "orderSize": 100,
    "gridSpacing": 400
  }
}
```

## Examples

```bash
curl -X POST "http://localhost:3000/api/v1/strategy/grid" \
  -H "Content-Type: application/json" \
  -d '{
    "exchange": "mexc",
    "symbol": "BTC/USDT",
    "lowerPrice": 40000,
    "upperPrice": 44000,
    "gridLevels": 10,
    "orderSize": 100
  }'
```

## Errors

| Code | Error          | Description                    |
| ---- | -------------- | ------------------------------ |
| 400  | Invalid range  | lowerPrice >= upperPrice       |
| 400  | Invalid levels | gridLevels < 2 or > 100        |
| 500  | Start failed   | Strategy initialization failed |


# DELETE /strategy/grid

Stop a running grid strategy.

## Request

```
DELETE /api/v1/strategy/grid
Content-Type: application/json
```

### Body

```json
{
  "id": "grid-mexc-BTC-USDT-1710000000000",
  "cancelOrders": true
}
```

### Parameters

| Parameter    | Type    | Required | Default | Description            |
| ------------ | ------- | -------- | ------- | ---------------------- |
| id           | string  | ✅        | —       | Strategy ID            |
| cancelOrders | boolean | ❌        | true    | Cancel all open orders |

## Response

```json
{
  "success": true,
  "id": "grid-mexc-BTC-USDT-1710000000000",
  "message": "Strategy stopped and orders cancelled",
  "summary": {
    "runningTime": 3600000,
    "filledOrders": 12,
    "profit": 45.50
  }
}
```

### Summary Fields

| Field        | Type   | Description         |
| ------------ | ------ | ------------------- |
| runningTime  | number | Running time in ms  |
| filledOrders | number | Total orders filled |
| profit       | number | Estimated profit    |

## Examples

```bash
curl -X DELETE "http://localhost:3000/api/v1/strategy/grid" \
  -H "Content-Type: application/json" \
  -d '{"id": "grid-mexc-BTC-USDT-1710000000000"}'
```

## Errors

| Code | Error     | Description               |
| ---- | --------- | ------------------------- |
| 404  | Not found | Strategy ID doesn't exist |


# GET /strategy/grid/status

Get status of grid strategies.

## Request

```
GET /api/v1/strategy/grid/status?id={id}
```

### Parameters

| Parameter | Type   | Required | Description                          |
| --------- | ------ | -------- | ------------------------------------ |
| id        | string | ❌        | Strategy ID (returns all if omitted) |

## Response

```json
{
  "strategies": [
    {
      "id": "grid-mexc-BTC-USDT-1710000000000",
      "status": "running",
      "exchange": "mexc",
      "symbol": "BTC/USDT",
      "lowerPrice": 40000,
      "upperPrice": 44000,
      "gridLevels": 10,
      "orderSize": 100,
      "openOrders": 8,
      "filledOrders": 4,
      "profit": 22.50,
      "startedAt": 1710000000000,
      "runningTime": 1800000
    }
  ],
  "count": 1
}
```

### Status Values

| Status  | Description                 |
| ------- | --------------------------- |
| idle    | Initialized but not started |
| running | Actively trading            |
| stopped | Manually stopped            |
| error   | Error occurred              |

## Examples

```bash
# Get all strategies
curl "http://localhost:3000/api/v1/strategy/grid/status"

# Get specific strategy
curl "http://localhost:3000/api/v1/strategy/grid/status?id=grid-mexc-BTC-USDT-xxx"
```

## Errors

| Code | Error     | Description               |
| ---- | --------- | ------------------------- |
| 404  | Not found | Strategy ID doesn't exist |


# Cardano DEX

Cardano DEX integration via Iris Protocol for token pricing and pool discovery.

## Endpoints

| Method | Endpoint                                                       | Description              |
| ------ | -------------------------------------------------------------- | ------------------------ |
| GET    | [/cardano/price/:symbol](/api-reference/cardano/cardano-price) | Get token price          |
| GET    | [/cardano/pools/:symbol](/api-reference/cardano/cardano-pools) | Discover liquidity pools |

## Supported Tokens

| Symbol | Name    | Policy ID   |
| ------ | ------- | ----------- |
| INDY   | Indigo  | 533bb94a... |
| SNEK   | Snek    | 279c909f... |
| NIGHT  | Night   | 0691b2fe... |
| MIN    | Minswap | 29d222ce... |

## Price Calculation

Prices are calculated as TOKEN/USDT via ADA bridge:

1. Fetch TOKEN/ADA price from Cardano DEXs
2. Fetch ADA/USDT from CEX (Kraken)
3. Calculate: TOKEN/USDT = TOKEN/ADA × ADA/USDT

## Data Source

All data comes from [Iris Protocol](https://iris.indigoprotocol.io), which aggregates liquidity from:

* Minswap
* SundaeSwap
* WingRiders
* Spectrum
* MuesliSwap
* VyFinance


# GET /cardano/price/:symbol

Get aggregated price for a Cardano token.

## Request

```
GET /api/v1/cardano/price/{symbol}
```

### Parameters

| Parameter | Type   | Required | Description                           |
| --------- | ------ | -------- | ------------------------------------- |
| symbol    | string | ✅        | Token symbol (INDY, SNEK, NIGHT, MIN) |

## Response

```json
{
  "symbol": "INDY/USDT",
  "price": 0.52,
  "confidence": 0.95,
  "sources": [
    {
      "id": "minswap-pool-1",
      "name": "Minswap INDY/ADA",
      "exchange": "cardano"
    },
    {
      "id": "sundae-pool-1",
      "name": "SundaeSwap INDY/ADA",
      "exchange": "cardano"
    }
  ],
  "timestamp": "2026-03-14T00:00:00.000Z"
}
```

### Response Fields

| Field      | Type   | Description               |
| ---------- | ------ | ------------------------- |
| symbol     | string | Trading pair (TOKEN/USDT) |
| price      | number | Price in USDT             |
| confidence | number | Confidence score (0-1)    |
| sources    | array  | Price sources used        |
| timestamp  | string | ISO 8601 timestamp        |

## Examples

```bash
# Get INDY price
curl "http://localhost:3000/api/v1/cardano/price/INDY"

# Case insensitive
curl "http://localhost:3000/api/v1/cardano/price/snek"
```

## Errors

| Code | Error              | Description                 |
| ---- | ------------------ | --------------------------- |
| 400  | Unsupported token  | Token not in supported list |
| 500  | Price fetch failed | Iris API error              |


# GET /cardano/pools/:symbol

Discover liquidity pools for a Cardano token.

## Request

```
GET /api/v1/cardano/pools/{symbol}?minLiquidity={minLiquidity}&limit={limit}
```

### Parameters

| Parameter    | Type   | Required | Default | Description        |
| ------------ | ------ | -------- | ------- | ------------------ |
| symbol       | string | ✅        | —       | Token symbol       |
| minLiquidity | number | ❌        | 0       | Minimum TVL in ADA |
| limit        | number | ❌        | 10      | Max pools (1-50)   |

## Response

```json
{
  "symbol": "INDY",
  "pools": [
    {
      "dex": "Minswap",
      "identifier": "pool-abc123",
      "tvl": 500000,
      "price": 1.85,
      "reserveA": 270000,
      "reserveB": 500000,
      "tokenA": "INDY",
      "tokenB": "ADA"
    },
    {
      "dex": "SundaeSwap",
      "identifier": "pool-def456",
      "tvl": 250000,
      "price": 1.84,
      "reserveA": 136000,
      "reserveB": 250000,
      "tokenA": "INDY",
      "tokenB": "ADA"
    }
  ],
  "count": 2,
  "timestamp": "2026-03-14T00:00:00.000Z"
}
```

### Pool Fields

| Field      | Type   | Description              |
| ---------- | ------ | ------------------------ |
| dex        | string | DEX name                 |
| identifier | string | Pool identifier          |
| tvl        | number | Total value locked (ADA) |
| price      | number | Token price in ADA       |
| reserveA   | number | Reserve of token A       |
| reserveB   | number | Reserve of token B       |
| tokenA     | string | First token symbol       |
| tokenB     | string | Second token symbol      |

## Examples

```bash
# Get top 5 INDY pools
curl "http://localhost:3000/api/v1/cardano/pools/INDY?limit=5"

# Filter by TVL
curl "http://localhost:3000/api/v1/cardano/pools/SNEK?minLiquidity=100000"
```

## Errors

| Code | Error             | Description                 |
| ---- | ----------------- | --------------------------- |
| 400  | Unsupported token | Token not in supported list |
| 500  | Discovery failed  | Iris API error              |


# Price Comparison

Cross-exchange price comparison for arbitrage detection.

## Endpoints

| Method | Endpoint                                                        | Description                     |
| ------ | --------------------------------------------------------------- | ------------------------------- |
| GET    | [/price/compare](/api-reference/price-comparison/price-compare) | Compare prices across exchanges |

## Use Cases

* **Arbitrage Detection** — Find price differences between exchanges
* **Best Execution** — Determine optimal exchange for trading
* **Market Analysis** — Monitor cross-exchange spreads


# GET /price/compare

Compare prices for a trading pair across multiple exchanges.

## Request

```
GET /api/v1/price/compare?symbol={symbol}&exchanges={exchanges}
```

### Parameters

| Parameter | Type   | Required | Default | Description                  |
| --------- | ------ | -------- | ------- | ---------------------------- |
| symbol    | string | ✅        | —       | Trading pair                 |
| exchanges | string | ❌        | all     | Comma-separated exchange IDs |

## Response

```json
{
  "symbol": "BTC/USDT",
  "prices": [
    {
      "exchange": "mexc",
      "price": 42150.00,
      "bid": 42148.00,
      "ask": 42152.00,
      "spread": 4.00,
      "spreadPercent": 0.0095,
      "timestamp": 1710000000000
    },
    {
      "exchange": "gateio",
      "price": 42145.00,
      "bid": 42143.00,
      "ask": 42147.00,
      "spread": 4.00,
      "spreadPercent": 0.0095,
      "timestamp": 1710000000000
    }
  ],
  "analysis": {
    "lowestAsk": {
      "exchange": "gateio",
      "price": 42147.00
    },
    "highestBid": {
      "exchange": "mexc",
      "price": 42148.00
    },
    "spread": 1.00,
    "spreadPercent": 0.0024,
    "arbitrageOpportunity": true
  },
  "timestamp": 1710000000000
}
```

### Analysis Fields

| Field                | Type    | Description                   |
| -------------------- | ------- | ----------------------------- |
| lowestAsk            | object  | Best exchange to buy          |
| highestBid           | object  | Best exchange to sell         |
| spread               | number  | Cross-exchange spread         |
| spreadPercent        | number  | Spread as percentage          |
| arbitrageOpportunity | boolean | True if profitable arb exists |

## Examples

```bash
# Compare across all exchanges
curl "http://localhost:3000/api/v1/price/compare?symbol=BTC/USDT"

# Compare specific exchanges
curl "http://localhost:3000/api/v1/price/compare?symbol=ETH/USDT&exchanges=mexc,kraken"
```

## Arbitrage Detection

When `arbitrageOpportunity` is `true`:

* Buy at `lowestAsk.exchange` at `lowestAsk.price`
* Sell at `highestBid.exchange` at `highestBid.price`
* Gross profit = `spread`

⚠️ Consider trading fees, withdrawal fees, and transfer times before executing.

## Errors

| Code | Error          | Description                  |
| ---- | -------------- | ---------------------------- |
| 400  | Invalid symbol | Symbol format incorrect      |
| 500  | Fetch failed   | One or more exchanges failed |


# Cardano Tokens

Quick guide to add and test Cardano tokens before market making.

## 🔍 Check Supported Tokens

```bash
openmm pool-discovery supported
```

## ➕ Add New Token

### 1. Get Token Info

Find these on [Cardanoscan.io](https://cardanoscan.io):

* **Policy ID**
* **Asset Name** (hex)

### 2. Add to Configuration

Edit `src/config/price-aggregation.ts`:

```typescript
'YOUR_TOKEN': {
  symbol: 'YOUR_TOKEN',
  policyId: 'policy_id_here',
  assetName: 'hex_asset_name',
  minLiquidityThreshold: 50000
}
```

Or generate with CLI:

```bash
openmm pool-discovery custom <POLICY_ID> <ASSET_NAME_HEX> <SYMBOL>
```

## 🧪 Test Before Market Making

### 1. Find Pools

```bash
openmm pool-discovery discover YOUR_TOKEN --limit 3
```

✅ **Look for**: Active pools (✅), TVL > $25K, multiple DEXes

### 2. Test Pricing

```bash
openmm pool-discovery prices YOUR_TOKEN
```

***


# Grid Strategy

This guide explains how to run the Grid Trading Strategy using OpenMM's unified CLI interface.

## Prerequisites

1. **Environment Setup**

   ```bash
   # Set your exchange API credentials

   # For MEXC
   export MEXC_API_KEY="your_api_key"
   export MEXC_SECRET="your_secret_key"

   # For Bitget
   export BITGET_API_KEY="your_api_key"
   export BITGET_SECRET="your_secret_key"
   export BITGET_PASSPHRASE="your_passphrase"

   # For Gate.io
   export GATEIO_API_KEY="your_api_key"
   export GATEIO_SECRET="your_secret_key"

   # For Kraken
   export KRAKEN_API_KEY="your_api_key"
   export KRAKEN_SECRET="your_secret_key"
   ```
2. **Install Dependencies**

   ```bash
   npm install
   npm run build
   ```

## Quick Start

### Basic Grid Strategy

**MEXC Example:**

```bash
# Start grid trading with default settings on MEXC
openmm trade --strategy grid --exchange mexc --symbol INDY/USDT
```

**Bitget Example:**

```bash
# Start grid trading with default settings on Bitget
openmm trade --strategy grid --exchange bitget --symbol SNEK/USDT
```

**Gate.io Example:**

```bash
# Start grid trading with default settings on Gate.io
openmm trade --strategy grid --exchange gateio --symbol SNEK/USDT
```

**Kraken Example:**

```bash
# Start grid trading with default settings on Kraken
openmm trade --strategy grid --exchange kraken --symbol ADA/EUR
```

### Custom Configuration

**MEXC Advanced Grid:**

```bash
# Advanced grid with custom parameters on MEXC
openmm trade --strategy grid --exchange mexc --symbol INDY/USDT \
  --levels 5 \
  --spacing 0.02 \
  --size 50 \
  --max-position 0.6 \
  --safety-reserve 0.3
```

**Bitget Advanced Grid:**

```bash
# Advanced grid with custom parameters on Bitget
openmm trade --strategy grid --exchange bitget --symbol SNEK/USDT \
  --levels 3 \
  --spacing 0.015 \
  --size 25 \
  --max-position 0.7 \
  --safety-reserve 0.3
```

**Kraken Advanced Grid:**

```bash
# Advanced grid with custom parameters on Kraken
openmm trade --strategy grid --exchange kraken --symbol SNEK/EUR \
  --levels 4 \
  --spacing 0.01 \
  --size 15 \
  --max-position 0.6 \
  --safety-reserve 0.25
```

## Command Options

### Required Parameters

* `--strategy grid` - Specifies grid trading strategy
* `--exchange <exchange>` - Exchange to trade on (supports: `mexc`, `bitget`, `gateio`, `kraken`)
* `--symbol <symbol>` - Trading pair (e.g., INDY/USDT, SNEK/USDT, ADA/EUR, BTC/USD)

### Grid Parameters

* `--levels <number>` - Grid levels each side (default: 5, max: 10, total orders = levels x 2)
* `--spacing <decimal>` - Base price spacing between levels (default: 0.02 = 2%)
* `--size <number>` - Base order size in quote currency (default: 50)
* `--confidence <decimal>` - Minimum price confidence to trade (default: 0.6 = 60%)
* `--deviation <decimal>` - Price deviation % to trigger grid recreation (default: 0.015 = 1.5%)
* `--debounce <ms>` - Delay between grid adjustments (default: 2000ms)
* `--max-position <decimal>` - Maximum position size as % of balance (default: 0.8 = 80%)
* `--safety-reserve <decimal>` - Safety reserve as % of balance (default: 0.2 = 20%)
* `--dry-run` - Simulate trading without placing real orders

### Dynamic Grid Parameters

These parameters control how order levels and sizes are distributed across the grid:

* `--spacing-model <model>` - How spacing between levels is calculated (default: `linear`)
  * `linear` - Equal spacing between all levels
  * `geometric` - Spacing increases by a factor per level (wider gaps at outer levels)
  * `custom` - User-defined spacing offsets via grid profile file
* `--spacing-factor <number>` - Geometric spacing multiplier per level (default: 1.3)
* `--size-model <model>` - How order sizes are distributed across levels (default: `flat`)
  * `flat` - Equal size for all levels
  * `pyramidal` - Larger sizes near center price, smaller at outer levels
  * `custom` - User-defined weight multipliers via grid profile file
* `--grid-profile <path>` - Load complete grid configuration from a JSON profile file

### Volatility Parameters

These parameters control automatic spread adjustment based on market volatility:

* `--volatility` - Enable volatility-based dynamic spread adjustment (off by default)
* `--volatility-low <decimal>` - Low volatility threshold (default: 0.02 = 2%). Below this, grid spacing stays normal.
* `--volatility-high <decimal>` - High volatility threshold (default: 0.05 = 5%). Above this, grid spacing is widened maximally.

## Dynamic Grid Configuration

### Spacing Models

**Linear (default):** Equal spacing between all levels. With `--spacing 0.02` and 5 levels, each level is 2% apart:

```
Level 1: 2% from center
Level 2: 4% from center
Level 3: 6% from center
Level 4: 8% from center
Level 5: 10% from center
```

**Geometric:** Each level's gap is multiplied by the spacing factor. This creates tighter spacing near the center price and wider gaps at the outer levels, which is more realistic for market making:

```bash
openmm trade --strategy grid --exchange kraken --symbol BTC/USD \
  --levels 5 --spacing 0.005 --spacing-model geometric --spacing-factor 1.5
```

With `--spacing 0.005` and `--spacing-factor 1.5`:

```
Level 1: 0.50% from center (gap: 0.50%)
Level 2: 1.25% from center (gap: 0.75%)
Level 3: 2.38% from center (gap: 1.13%)
Level 4: 4.06% from center (gap: 1.69%)
Level 5: 6.59% from center (gap: 2.53%)
```

**Custom:** Define exact spacing offsets per level using a grid profile file (see Grid Profiles section below).

### Size Models

**Flat (default):** All levels get equal order sizes.

**Pyramidal:** Larger orders near the center price where fills are more likely, tapering at outer levels:

```bash
openmm trade --strategy grid --exchange mexc --symbol INDY/USDT \
  --levels 5 --size 50 --size-model pyramidal
```

**Custom:** Define exact size weight multipliers per level using a grid profile file.

### Grid Profiles

Grid profiles are JSON files that define a complete grid configuration. This is useful for:

* Full per-level control over spacing and sizing
* Sharing and version-controlling configurations
* Quickly switching between strategies

**Basic profile (geometric spacing, pyramidal sizing):**

```json
{
  "name": "balanced-geometric",
  "description": "Geometric spacing with pyramidal sizing for balanced market making",
  "levels": 10,
  "spacingModel": "geometric",
  "baseSpacing": 0.005,
  "spacingFactor": 1.3,
  "sizeModel": "pyramidal",
  "baseSize": 50
}
```

**Custom profile (full per-level control):**

```json
{
  "name": "custom-aggressive",
  "description": "Custom spacing and sizing for aggressive market making",
  "levels": 5,
  "spacingModel": "custom",
  "customSpacings": [0.003, 0.008, 0.015, 0.025, 0.04],
  "sizeModel": "custom",
  "sizeWeights": [2.0, 1.5, 1.0, 0.7, 0.4],
  "baseSpacing": 0.003,
  "baseSize": 50
}
```

**Using a profile:**

```bash
openmm trade --strategy grid --exchange gateio --symbol SNEK/USDT \
  --grid-profile ./profiles/balanced-geometric.json
```

Profile values override corresponding CLI parameters.

## Trading Examples

### Conservative Trading Strategies

**MEXC - Conservative INDY Trading:**

```bash
openmm trade --strategy grid --exchange mexc --symbol INDY/USDT \
  --levels 3 \
  --spacing 0.01
```

**Bitget - Conservative SNEK Trading:**

```bash
openmm trade --strategy grid --exchange bitget --symbol SNEK/USDT \
  --levels 2 \
  --spacing 0.02 \
  --size 20
```

**Kraken - Conservative ADA Trading:**

```bash
openmm trade --strategy grid --exchange kraken --symbol ADA/EUR \
  --levels 3 \
  --spacing 0.015 \
  --size 10
```

### Active Trading Strategies

**MEXC - Active BTC Trading:**

```bash
openmm trade --strategy grid --exchange mexc --symbol BTC/USDT \
  --levels 7 \
  --spacing 0.005 \
  --size 25
```

**Bitget - Active NIGHT Trading:**

```bash
openmm trade --strategy grid --exchange bitget --symbol NIGHT/USDT \
  --levels 5 \
  --spacing 0.025 \
  --size 30 \
  --max-position 0.6
```

**Kraken - Active ETH Trading:**

```bash
openmm trade --strategy grid --exchange kraken --symbol ETH/USD \
  --levels 6 \
  --spacing 0.008 \
  --size 40 \
  --max-position 0.7
```

### Dynamic Grid Strategies

**1. Linear Spacing + Flat Sizing (default behavior):**

```bash
openmm trade --strategy grid --exchange kraken --symbol SNEK/EUR \
  --levels 5 \
  --spacing 0.02 \
  --size 5
```

**2. Geometric Spacing + Flat Sizing:**

```bash
openmm trade --strategy grid --exchange kraken --symbol SNEK/EUR \
  --levels 10 \
  --spacing 0.003 \
  --spacing-model geometric \
  --spacing-factor 1.3 \
  --size 5
```

**3. Geometric Spacing + Pyramidal Sizing:**

```bash
openmm trade --strategy grid --exchange kraken --symbol SNEK/EUR \
  --levels 10 \
  --spacing 0.005 \
  --spacing-model geometric \
  --spacing-factor 1.5 \
  --size-model pyramidal \
  --size 5
```

**4. Linear Spacing + Pyramidal Sizing:**

```bash
openmm trade --strategy grid --exchange kraken --symbol SNEK/EUR \
  --levels 8 \
  --spacing 0.01 \
  --size-model pyramidal \
  --size 5
```

**5. Geometric with Aggressive Factor (wider outer levels):**

```bash
openmm trade --strategy grid --exchange kraken --symbol SNEK/EUR \
  --levels 10 \
  --spacing 0.002 \
  --spacing-model geometric \
  --spacing-factor 2.0 \
  --size-model pyramidal \
  --size 5
```

**6. Profile-Based Grid (custom JSON config):**

```bash
openmm trade --strategy grid --exchange gateio --symbol SNEK/USDT \
  --grid-profile ./profiles/aggressive.json
```

**7. Multi-Exchange Dynamic Grid:**

```bash
# MEXC - Geometric + Pyramidal
openmm trade --strategy grid --exchange mexc --symbol INDY/USDT \
  --levels 10 \
  --spacing 0.005 \
  --spacing-model geometric \
  --spacing-factor 1.3 \
  --size-model pyramidal \
  --size 5

# Bitget - Linear + Pyramidal
openmm trade --strategy grid --exchange bitget --symbol SNEK/USDT \
  --levels 7 \
  --spacing 0.01 \
  --size-model pyramidal \
  --size 5

# Gate.io - Geometric + Pyramidal
openmm trade --strategy grid --exchange gateio --symbol SNEK/USDT \
  --levels 8 \
  --spacing 0.004 \
  --spacing-model geometric \
  --spacing-factor 1.4 \
  --size-model pyramidal \
  --size 5
```

### Volatility-Based Spread Adjustment

When enabled with `--volatility`, the grid automatically widens during volatile market conditions and tightens when the market calms down. The system tracks price changes over a rolling 5-minute window (10 samples at 30-second intervals) and calculates volatility as the price range divided by the average price.

**How it works:**

* Volatility below low threshold (default 2%): Normal grid spacing (multiplier 1.0x)
* Volatility between thresholds: Elevated spacing (multiplier 1.5x)
* Volatility above high threshold (default 5%): Wide spacing (multiplier 2.0x)

**8. Volatility with default thresholds (2% low, 5% high):**

```bash
openmm trade --strategy grid --exchange kraken --symbol SNEK/EUR \
  --levels 5 \
  --spacing 0.01 \
  --size 5 \
  --volatility
```

**9. Volatility with custom thresholds (tighter sensitivity):**

```bash
openmm trade --strategy grid --exchange kraken --symbol SNEK/EUR \
  --levels 5 \
  --spacing 0.01 \
  --size 5 \
  --volatility \
  --volatility-low 0.01 \
  --volatility-high 0.03
```

**10. Volatility combined with geometric spacing:**

```bash
openmm trade --strategy grid --exchange mexc --symbol INDY/USDT \
  --levels 10 \
  --spacing 0.005 \
  --spacing-model geometric \
  --spacing-factor 1.3 \
  --size-model pyramidal \
  --size 5 \
  --volatility
```

### Test Mode (No Real Orders)

**MEXC Test:**

```bash
openmm trade --strategy grid --exchange mexc --symbol INDY/USDT --dry-run
```

**Bitget Test:**

```bash
openmm trade --strategy grid --exchange bitget --symbol SNEK/USDT --dry-run
```

**Gate.io Test:**

```bash
openmm trade --strategy grid --exchange gateio --symbol SNEK/USDT --dry-run
```

**Kraken Test:**

```bash
openmm trade --strategy grid --exchange kraken --symbol ADA/EUR --dry-run
```

**Dynamic Grid Test:**

```bash
openmm trade --strategy grid --exchange mexc --symbol INDY/USDT \
  --levels 10 --spacing-model geometric --dry-run
```

**Volatility Test:**

```bash
openmm trade --strategy grid --exchange kraken --symbol SNEK/EUR \
  --levels 5 --spacing 0.01 --size 5 --volatility --dry-run
```

## Risk Management

The Grid Strategy includes built-in risk management:

### Configurable Risk Limits

Users can customize risk management through CLI parameters:

* `--max-position 0.6` - Use max 60% of balance for trading (default: 80%)
* `--safety-reserve 0.3` - Keep 30% as safety reserve (default: 20%)
* `--confidence 0.8` - Require 80% price confidence (default: 60%)

### Automatic Position Sizing

When using flat sizing, the system distributes the base order size equally across all levels. With pyramidal sizing, larger allocations are placed near the center price where fills are more likely, with smaller orders at the edges.

Total allocation is automatically capped at 80% of available balance regardless of the size model used.

### Price Confidence Filtering

* Only executes trades when price confidence >= minimum threshold
* Sources price data from Cardano DEX via Iris API
* Prevents trading on unreliable price data

### Dynamic Grid Management

* Recreates grid when orders are filled
* Adjusts to significant price movements (configurable via `--deviation`)
* Cancels and replaces orders as needed
* Debounce mechanism prevents rapid-fire grid recreation

## Monitoring Your Strategy

### Real-time Updates

The strategy provides live feedback:

```
🚀 Starting Trading Strategy
Strategy: GRID
Exchange: KRAKEN
Symbol: BTC/USD
Grid Levels: 10 per side (20 total)
Grid Spacing: 0.3%
Spacing Model: geometric
Spacing Factor: 1.3
Size Model: pyramidal
Order Size: $50
Max Position: 80%
Safety Reserve: 20%

⚙️  Creating strategy...
✅ Strategy initialized successfully
🔄 Starting strategy...
📊 Grid Configuration:
  Levels: 10 per side (20 total orders)
  Spacing Model: geometric
  Base Spacing: 0.30%
  Spacing Factor: 1.3
  Size Model: pyramidal
  Base Size: $50
✅ Strategy is now running!
Press Ctrl+C to stop the strategy gracefully
```

### Graceful Shutdown

```bash
# Stop the strategy cleanly
Ctrl+C
```

The system will:

1. Cancel all open orders
2. Disconnect from exchange
3. Display final status

## Troubleshooting

### Common Issues

**Invalid credentials (MEXC):**

```
Error: MEXC credentials not found
```

Solution: Verify `MEXC_API_KEY` and `MEXC_SECRET` environment variables

**Invalid credentials (Bitget):**

```
Error: Bitget credentials validation failed
```

Solution: Verify `BITGET_API_KEY`, `BITGET_SECRET`, and `BITGET_PASSPHRASE` environment variables

**Invalid credentials (Gate.io):**

```
Error: Gate.io credentials not found
```

Solution: Verify `GATEIO_API_KEY` and `GATEIO_SECRET` environment variables

**Invalid credentials (Kraken):**

```
Error: Kraken authentication failed
```

Solution: Verify `KRAKEN_API_KEY` and `KRAKEN_SECRET` environment variables

**Minimum order value (Bitget/MEXC):**

```
Error: Bitget order value 0.50 USDT is below minimum 1 USDT
```

Solution: Increase `--size` parameter or reduce number of `--levels` to ensure each order meets 1 USDT minimum

**Minimum order value (Kraken):**

```
Error: Kraken order value 3.50 EUR is below minimum 5 EUR
```

Solution: Increase `--size` parameter or reduce number of `--levels` to ensure each order meets 5 EUR/USD minimum

**Low price confidence:**

```
Error: Price confidence too low: 0.4 < 0.6
```

Solution: Lower `--confidence` threshold or wait for better price data

**Price precision error (Bitget):**

```
Error: param price scale error
```

Solution: This is automatically handled by the system's precision formatting. If you see this error, please report it as it indicates a system issue.

**Insufficient balance:**

```
Error: No balance found for USDT
```

Solution: Ensure sufficient USDT balance in your exchange account

**Invalid grid profile:**

```
Error: Grid profile file not found: ./profiles/my-config.json
```

Solution: Verify the profile file path exists and contains valid JSON

**Invalid spacing/size model:**

```
Error: Invalid spacing model: abc. Must be: linear, geometric, or custom
```

Solution: Use one of the supported models: `linear`, `geometric`, or `custom` for spacing; `flat`, `pyramidal`, or `custom` for sizing

### Exchange-Specific Notes

**Bitget Requirements:**

* Minimum order value: 1 USDT per order
* Price precision: 6 decimal places for SNEK/NIGHT pairs
* Quantity precision: 2 decimal places for SNEK/INDY/NIGHT pairs
* Requires API key, secret, and passphrase for authentication

**MEXC Requirements:**

* Minimum order value: 1 USDT per order
* Flexible precision handling
* Requires API key and secret for authentication

**Gate.io Requirements:**

* Minimum order value: 1 USDT per order
* Requires API key and secret for authentication

**Kraken Requirements:**

* Minimum order value: 5 EUR/USD/GBP per order
* Price precision: Maximum 6 decimal places
* Quantity precision: 2 decimal places for ADA, 6-8 for BTC/ETH
* Requires API key and secret for authentication
* Supports major fiat pairs (EUR, USD, GBP) and crypto pairs


# Contributing


