openapi: 3.0.0
info:
  title: Tradegrub Published API
  version: 1.0.0
  description: >-
    The Tradegrub API provides everything you need to connect to market data
    and manage your trading activities across multiple exchanges.


    **Base URL:** `https://api.tradegrub.com`


    **Authentication:** All endpoints require HTTP Basic Auth using your
    API key (username) and secret key (password).
servers:
  - url: https://api.tradegrub.com
    description: Production

tags:
  - name: General
    description: Core market data — list exchanges, browse markets, fetch tickers, pull OHLCV candles, chart history, and currency rates.
  - name: Fundamentals
    description: Balance sheets, income statements, and on-chain metrics for stocks (SEC filings) and crypto assets.
  - name: News
    description: Latest headlines and articles for any stock or crypto symbol.
  - name: Signals
    description: Receive TradingView-style webhook alerts and auto-execute trades on connected exchanges.
  - name: Auth
    description: Link an exchange account by submitting API credentials and receiving a session token.
  - name: Orders
    description: Place, list, and cancel orders. View positions, balances, and trade history.
  - name: Quotes
    description: Quote/OHLCV data from specific sources
  - name: Risk
    description: Create portfolio rules that monitor conditions and trigger alerts or auto-trades.
  - name: Wallet
    description: Generate wallets, check balances, send transactions, and view history on supported blockchains.


paths:
  # ─── General ───────────────────────────────────────────────────────────
  /v1/exchange/ping:
    get:
      summary: Ping
      description: Quick health check — returns `pong` if the API is up.
      tags:
        - General
      security:
        - BasicAuth: []
      responses:
        '200':
          description: Service is running
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PingResponse'
              example:
                success: pong

  /v1/exchanges:
    get:
      summary: List Exchanges
      description: Returns every exchange supported by Tradegrub (e.g., alpaca, binance, coinbase).
      tags:
        - General
      security:
        - BasicAuth: []
      responses:
        '200':
          description: List of supported exchange names
          content:
            application/json:
              schema:
                type: array
                items:
                  type: string
              example:
                - alpaca
                - binance
                - binanceus
                - coinbase
                - kraken
                - bitfinex

  /v1/exchange/{exchange_name}/markets:
    get:
      summary: List Markets
      description: Returns all trading pairs on an exchange with their limits, precision, and base/quote info.
      tags:
        - General
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
      responses:
        '200':
          description: List of markets
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Market'
              example:
                - base: BTC
                  exchange: binance
                  id: BTCUSDT
                  info:
                    baseCurrency: BTC
                    maxBaseOrderSize: "10"
                    minOrderValue: "1"
                    pricePrecision: "2"
                  limits:
                    amount: { max: 100, min: 0.001 }
                    cost: { max: 10000, min: 1 }
                  precision:
                    amount: 2
                    price: 2
                  quote: USDT
                  symbol: BTC/USDT

  /v1/exchange/{exchange_name}/currencies:
    get:
      summary: List Currencies
      description: Returns all currencies on an exchange with deposit/withdrawal limits, fees, and network info.
      tags:
        - General
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
      responses:
        '200':
          description: Map of currency code to currency details
          content:
            application/json:
              schema:
                type: object
                additionalProperties:
                  $ref: '#/components/schemas/Currency'

  /v1/exchange/{exchange_name}/tickers:
    get:
      summary: Get Tickers
      description: Returns live price, high, low, and volume for trading pairs. Optionally filter by symbol.
      tags:
        - General
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
        - name: symbols
          in: query
          schema:
            type: string
          example: BTC/USD,ETH/USD
          description: "Comma-separated list of symbols to filter (e.g., BTC/USD,ETH/USD)"
      responses:
        '200':
          description: Ticker data
          content:
            application/json:
              schema:
                type: object
                additionalProperties:
                  $ref: '#/components/schemas/Ticker'
              example:
                "00/USD":
                  ask: null
                  askVolume: null
                  average: 0.0044
                  baseVolume: 1337908.86
                  bid: null
                  bidVolume: null
                  change: 0.0002
                  close: 0.0045
                  datetime: null
                  high: null
                  indexPrice: null
                  info: {}
                  last: 0.0045
                  low: null
                  markPrice: null
                  open: 0.0043
                  percentage: 4.65
                  previousClose: null
                  quoteVolume: 6020.59
                  symbol: "00/USD"
                  timestamp: null
                  vwap: 0.0045

  /v1/exchange/{exchange_name}/OHLCV:
    get:
      summary: Get OHLCV
      description: Returns candlestick data (open, high, low, close, volume) for a symbol at the specified frequency and period.
      tags:
        - General
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
        - name: symbol
          in: query
          required: true
          schema:
            type: string
          example: BTC/USDT
        - name: frequency
          in: query
          required: true
          schema:
            type: integer
          example: 5
          description: Time interval for each candle
        - name: frequencyType
          in: query
          required: true
          schema:
            type: string
            enum:
              - minute
              - hour
              - daily
              - weekly
              - monthly
              - yearly
          example: minute
          description: Unit of the frequency
        - name: period
          in: query
          required: true
          schema:
            type: integer
          example: 1
          description: Duration of data to retrieve
        - name: periodType
          in: query
          required: true
          schema:
            type: string
            enum:
              - day
              - week
              - month
              - year
          example: day
          description: Unit of the period
      responses:
        '200':
          description: OHLCV candle data
          content:
            application/json:
              schema:
                type: object
                properties:
                  candles:
                    type: array
                    items:
                      $ref: '#/components/schemas/Candle'
              example:
                candles:
                  - open: 125078.95
                    high: 125078.95
                    low: 125000.01
                    close: 125000.01
                    volume: 26.56693
                    datetime: 1759647300000

  /v1/exchange/{exchange_name}/charts:
    get:
      summary: Get Chart Data
      description: Returns historical candlestick data between two timestamps. Use `from`/`to` as epoch milliseconds.
      tags:
        - General
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
        - name: symbol
          in: query
          required: true
          schema:
            type: string
          example: BTC/USDT
        - name: frequency
          in: query
          required: true
          schema:
            type: integer
          example: 1
          description: Time interval for each candle
        - name: frequencyType
          in: query
          required: true
          schema:
            type: string
            enum:
              - minute
              - hour
              - daily
              - weekly
              - monthly
              - yearly
          example: hour
          description: Unit of the frequency
        - name: from
          in: query
          required: true
          schema:
            type: integer
            format: int64
          example: 1715695197000
          description: Start timestamp in milliseconds since epoch
        - name: to
          in: query
          required: true
          schema:
            type: integer
            format: int64
          example: 1720432797000
          description: End timestamp in milliseconds since epoch
      responses:
        '200':
          description: Chart data
          content:
            application/json:
              schema:
                type: object
                properties:
                  candles:
                    type: array
                    description: "Each candle is an array: [timestamp, open, high, low, close, volume]"
                    items:
                      type: array
                      items:
                        type: number
                  empty:
                    type: boolean
                    description: "true if no data found for the given parameters"
                  symbol:
                    type: string
              example:
                candles:
                  - - 1738274400000
                    - 105200.01
                    - 105350.00
                    - 105094.57
                    - 105094.57
                    - 279.52567
                  - - 1738278000000
                    - 105094.57
                    - 105254.00
                    - 104693.82
                    - 104722.94
                    - 395.49962
                empty: false
                symbol: BTC/USDT

  /v1/exchange/{exchange_name}/rates:
    get:
      summary: Get Rates
      description: Returns fiat and crypto exchange rates relative to USD.
      tags:
        - General
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
      responses:
        '200':
          description: Exchange rates
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Rate'
                  timestamp:
                    type: integer
                    description: "Unix timestamp in milliseconds"
              example:
                data:
                  - currencySymbol: "$"
                    id: us-dollar
                    rateUsd: 1.0
                    symbol: USD
                    type: fiat
                timestamp: 1774329131916

  # ─── Fundamentals ─────────────────────────────────────────────────────
  /v1/fundamentals/ping:
    get:
      summary: Ping
      description: Quick health check — returns `pong` if the Fundamentals service is up.
      tags:
        - Fundamentals
      security:
        - BasicAuth: []
      responses:
        '200':
          description: Service is running
          content:
            text/plain:
              schema:
                type: string
              example: pong

  /v1/fundamentals:
    get:
      summary: Get Fundamentals
      description: >-
        Returns financials (stocks) or on-chain data (crypto).
        Use `EXCHANGE:TICKER` format — e.g., `NASDAQ:AAPL` or `BINANCE:BTCUSDT`.
        Pass `EXCHANGE:*` to get all symbols on an exchange.
      tags:
        - Fundamentals
      security:
        - BasicAuth: []
      parameters:
        - name: symbol
          in: query
          required: true
          schema:
            type: string
          example: "NASDAQ:AAPL"
          description: "Full symbol in EXCHANGE:TICKER format"
        - name: view
          in: query
          schema:
            type: string
            enum:
              - collapse
              - expand
          example: collapse
          description: >-
            collapse: returns a flat key-value structure grouped by period (q or y),
            with balance sheet, income statement, and cash flow as simple dictionaries.
            expand: returns a deeply nested structure with full SEC filing detail.
            Default: collapse.
        - name: period
          in: query
          schema:
            type: string
            enum:
              - 'q'
              - 'y'
          example: q
          description: >-
            Only used when view=collapse.
            q: latest quarterly filing (10-Q).
            y: latest annual filing (10-K).
            Default: q.
      responses:
        '200':
          description: >-
            For stocks: returns financial statements (balance sheet, income statement,
            cash flow) from SEC filings. For crypto: returns live market data
            (price, volume, market cap, supply).
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
              example:
                data:
                  q:
                    balanceSheet:
                      Cash and Cash Equivalents: 36269000000.0
                      Accounts Receivable: 27557000000.0
                    incomeStatement:
                      Net sales: 94036000000.0
                      Cost of sales: -50318000000.0
                      Gross margin: 43718000000.0
                    cashFlowStatement:
                      Cash generated by operating activities: 24068000000.0
                    filingDate: "2025-08-01"
                    periodEndDate: "2025-06-28"

  /v1/fundamentals/company-info:
    get:
      summary: Company Info
      description: "Returns company overview including SEC filings, leadership, and ownership data."
      tags:
        - Fundamentals
      security:
        - BasicAuth: []
      parameters:
        - name: symbol
          in: query
          required: true
          schema:
            type: string
          example: "NASDAQ:AAPL"
          description: "Full symbol in EXCHANGE:TICKER format"
      responses:
        '200':
          description: SEC filing data
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
              example:
                data:
                  filings:
                    - accessionNumber: "0001780525-26-000005"
                      description: ""
                      filingDate: "2026-03-17"
                      form: "4"

  /v1/fundamentals/insider-trading:
    get:
      summary: Insider Trading
      description: Returns insider buy/sell/exercise transactions with a 12-month summary of net activity.
      tags:
        - Fundamentals
      security:
        - BasicAuth: []
      parameters:
        - name: symbol
          in: query
          required: true
          schema:
            type: string
          example: "NASDAQ:AAPL"
          description: "Full symbol in EXCHANGE:TICKER format"
        - name: limit
          in: query
          schema:
            type: integer
          example: 10
          description: Number of transactions to return
      responses:
        '200':
          description: Insider trading data
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      summary:
                        type: object
                        properties:
                          buys12m:
                            type: object
                            properties:
                              trades:
                                type: integer
                              value:
                                type: number
                          sales12m:
                            type: object
                            properties:
                              trades:
                                type: integer
                              value:
                                type: number
                          exercises12m:
                            type: object
                            properties:
                              trades:
                                type: integer
                              value:
                                type: number
                          netInsider:
                            type: string
                      transactions:
                        type: array
                        items:
                          type: object
                          properties:
                            filingDate:
                              type: string
                            insiderName:
                              type: string
                            insiderTitle:
                              type: string
                            transactionType:
                              type: string
                            transactionTypeLabel:
                              type: string
                            shares:
                              type: number
                            pricePerShare:
                              type: number
                            value:
                              type: number
                            securityTitle:
                              type: string
              example:
                data:
                  summary:
                    buys12m:
                      trades: 0
                      value: 0
                    sales12m:
                      trades: 0
                      value: 0
                    exercises12m:
                      trades: 3
                      value: 0
                    netInsider: Selling
                  transactions:
                    - filingDate: "2026-03-17"
                      insiderName: "Jennifer Newstead"
                      insiderTitle: "SVP, GC and Secretary"
                      transactionType: "M"
                      transactionTypeLabel: "Exercise"
                      shares: 60208.0
                      pricePerShare: 0
                      value: 0
                      securityTitle: "Common Stock"

  /v1/fundamentals/analyst-ratings:
    get:
      summary: Analyst Ratings
      description: Returns analyst consensus (buy/hold/sell distribution, price targets) and individual analyst entries.
      tags:
        - Fundamentals
      security:
        - BasicAuth: []
      parameters:
        - name: symbol
          in: query
          required: true
          schema:
            type: string
          example: "NASDAQ:AAPL"
          description: "Full symbol in EXCHANGE:TICKER format"
      responses:
        '200':
          description: Analyst ratings data
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      consensus:
                        type: object
                        properties:
                          label:
                            type: string
                          totalAnalysts:
                            type: integer
                          avgTarget:
                            type: number
                          highTarget:
                            type: number
                          lowTarget:
                            type: number
                          distribution:
                            type: object
                            properties:
                              Buy:
                                type: integer
                              Hold:
                                type: integer
                              Sell:
                                type: integer
                      currentPrice:
                        type: number
                      entries:
                        type: array
                        items:
                          type: object
                          properties:
                            date:
                              type: string
                            firm:
                              type: string
                            action:
                              type: string
                            currentRating:
                              type: string
                            currentTarget:
                              type: number
                              nullable: true
                            prevRating:
                              type: string
                              nullable: true
                            prevTarget:
                              type: number
                              nullable: true
              example:
                data:
                  consensus:
                    label: Buy
                    totalAnalysts: 15
                    avgTarget: 310.79
                    highTarget: 350.0
                    lowTarget: 248.0
                    distribution:
                      Buy: 11
                      Hold: 3
                      Sell: 1
                  currentPrice: 251.49
                  entries:
                    - date: "Mar-23-26"
                      firm: "BofA Securities"
                      action: "Reiterated"
                      currentRating: "Buy"
                      currentTarget: 320.0
                      prevRating: null
                      prevTarget: 325.0

  /v1/fundamentals/earnings-date:
    get:
      summary: Earnings Date
      description: Returns the next expected earnings date for a stock.
      tags:
        - Fundamentals
      security:
        - BasicAuth: []
      parameters:
        - name: symbol
          in: query
          required: true
          schema:
            type: string
          example: "NASDAQ:AAPL"
          description: "Full symbol in EXCHANGE:TICKER format"
        - name: symbols
          in: query
          schema:
            type: string
          example: "AAPL,MSFT"
          description: "Comma-separated tickers for batch mode (e.g., AAPL,MSFT). When used, response is keyed by ticker."
      responses:
        '200':
          description: Earnings date info
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      earningsDate:
                        type: string
                        description: "Date in YYYY-MM-DD format"
                      marketTiming:
                        type: string
                        description: "AMC (after market close) or BMO (before market open)"
                      rawText:
                        type: string
                      source:
                        type: string
              example:
                data:
                  earningsDate: "2027-01-29"
                  marketTiming: "AMC"
                  rawText: "Jan 29 AMC"
                  source: "network"

  # ─── News ──────────────────────────────────────────────────────────────
  /v1/news/ping:
    get:
      summary: Ping
      description: Quick health check — returns `pong` if the News service is up.
      tags:
        - News
      security:
        - BasicAuth: []
      responses:
        '200':
          description: Service is running
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PingResponse'
              example:
                success: pong

  /v1/news:
    get:
      summary: Get News
      description: Returns recent news articles for a symbol. Use `exchange:ticker` format (e.g., `binance:BTC/USDT` or `goldfish:AAPL`).
      tags:
        - News
      security:
        - BasicAuth: []
      parameters:
        - name: symbol
          in: query
          required: true
          schema:
            type: string
          example: "binance:BTC/USDT"
          description: "Symbol in exchange:ticker format (e.g., binance:BTC/USDT or goldfish:AAPL)"
        - name: limit
          in: query
          schema:
            type: integer
          example: 5
          description: Number of articles to return
        - name: sort
          in: query
          schema:
            type: string
            enum:
              - asc
              - desc
            default: desc
          description: "Sort order by date"
      responses:
        '200':
          description: News articles
          content:
            application/json:
              schema:
                type: object
                properties:
                  count:
                    type: integer
                  results:
                    type: array
                    items:
                      $ref: '#/components/schemas/NewsArticle'
              example:
                count: 2
                results:
                  - description: "Apple (AAPL) stock has lost about 7%..."
                    link: "https://www.thestreet.com/..."
                    published_at: "2026-03-24T01:37:00+00:00"
                    source: Yahoo Finance
                    symbol: "NASDAQ:AAPL"
                    title: "Bank of America resets Apple price target"

  /v1/news/headline:
    get:
      summary: Get Headlines
      description: Returns top market headlines across all sources. No symbol required.
      tags:
        - News
      security:
        - BasicAuth: []
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
          example: 100
          description: "Number of headlines. Default: 100"
        - name: asset
          in: query
          schema:
            type: string
          description: "Filter by asset type"
        - name: market
          in: query
          schema:
            type: string
          description: "Filter by market"
      responses:
        '200':
          description: Top headlines
          content:
            application/json:
              schema:
                type: object
                properties:
                  count:
                    type: integer
                  results:
                    type: array
                    items:
                      $ref: '#/components/schemas/NewsArticle'
              example:
                count: 100
                results:
                  - symbol: "GENERAL"
                    title: "Japan reports lower-than-expected core inflation"
                    description: "The consumer price index fell to 1.3% last month..."
                    link: "https://www.cnbc.com/2026/03/24/japan-cpi.html"
                    published_at: "2026-03-24T06:41:33+00:00"
                    source: "CNBC"

  # ─── Signals ───────────────────────────────────────────────────────────
  /v1/webhook/ping:
    get:
      summary: Ping
      description: Quick health check — returns `pong` if the Signals service is up.
      tags:
        - Signals
      security:
        - BasicAuth: []
      responses:
        '200':
          description: Service is running
          content:
            text/plain:
              schema:
                type: string
              example: pong

  /v1/webhook:
    post:
      summary: Send Trading Signal
      description: Sends a buy/sell signal to an exchange. Supports fixed amounts, percentages, and currency-denominated quantities.
      tags:
        - Signals
      security:
        - BasicAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - apiKey
                - secret
                - ticker
                - exchange
                - strategy
                - bar
              properties:
                apiKey:
                  type: string
                  description: API key for exchange authentication
                secret:
                  type: string
                  description: Secret key for exchange authentication
                accountId:
                  type: string
                  description: Trading account identifier
                quantity:
                  type: string
                  description: "Amount to trade: fixed (e.g., '2 BTC'), percentage ('10%'), or currency value ('1000 USDT')"
                ticker:
                  type: string
                  description: Trading pair symbol (e.g., XRPUSDT)
                exchange:
                  type: string
                  description: Exchange name (e.g., binance)
                bar:
                  type: object
                  properties:
                    price:
                      type: number
                strategy:
                  type: object
                  properties:
                    signal:
                      type: string
                      enum:
                        - buy
                        - sell
                syminfo:
                  type: object
                  properties:
                    currency:
                      type: string
                    basecurrency:
                      type: string
                signalType:
                  type: string
                  description: "Signal type: Day, Swing, or Long. Default: Day"
            example:
              apiKey: your_api_key
              secret: your_secret_key
              accountId: acc123
              quantity: "50 USDT"
              ticker: TRXUSDT
              exchange: binance
              bar:
                price: 0.33
              strategy:
                signal: buy
              syminfo:
                currency: USDT
                basecurrency: TRX
              signalType: Day
      responses:
        '200':
          description: Order execution result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderResponse'

  # ─── Auth ──────────────────────────────────────────────────────────────
  /v1/exchange/{exchange_name}:
    post:
      summary: Generate Auth Token
      description: Submit exchange API credentials to receive a session token for authenticated trading endpoints.
      tags:
        - Auth
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - id
                - apiKey
                - secret
                - password
                - sandbox
              properties:
                id:
                  type: string
                  description: Exchange identifier (e.g., binanceus)
                apiKey:
                  type: string
                  description: Your exchange API key
                secret:
                  type: string
                  description: Your exchange secret key
                password:
                  type: string
                  description: Account password (if applicable, can be empty)
                sandbox:
                  type: boolean
                  description: "Use sandbox/testnet environment. Default: false"
                uid:
                  type: string
                  description: "Optional user identifier"
            example:
              id: binance
              apiKey: your_api_key
              secret: your_secret_key
              password: ""
              sandbox: false
      responses:
        '200':
          description: Authentication token
          content:
            application/json:
              schema:
                type: object
                properties:
                  token:
                    type: string
              example:
                token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

  # ─── Orders ────────────────────────────────────────────────────────────
  /v1/rms/ping:
    get:
      summary: Ping
      description: Quick health check — returns `pong` if the Orders service is up.
      tags:
        - Orders
      security:
        - BasicAuth: []
      responses:
        '200':
          description: Service is running
          content:
            text/plain:
              schema:
                type: string
              example: pong

  /v1/rms/exchange/{exchange_name}/order:
    post:
      summary: Place Order
      description: Places a market, limit, or stop order on the exchange. Returns the full execution result including fill details.
      tags:
        - Orders
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - symbol
                - login
                - type
                - side
                - amount
              properties:
                symbol:
                  type: string
                  description: Trading pair (e.g., TRX/USDT)
                login:
                  type: string
                  description: Exchange account login identifier
                type:
                  type: string
                  enum:
                    - market
                    - limit
                    - stop
                  description: Order type
                side:
                  type: string
                  enum:
                    - buy
                    - sell
                  description: Trade direction
                amount:
                  type: number
                  description: Quantity of base currency to trade
                price:
                  type: number
                  description: Price per unit (required for limit orders)
            example:
              symbol: BTC/USDT
              login: acc123
              type: limit
              side: buy
              amount: 10
              price: 1
      responses:
        '200':
          description: Order execution result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderResponse'

  /v1/rms/exchange/{exchange_name}/balances/accountInfo/{account_id}:
    get:
      summary: Get Account Info
      description: Returns account details including permissions, commission rates, and deposit/withdraw status.
      tags:
        - Orders
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
        - name: account_id
          in: path
          required: true
          schema:
            type: string
          example: acc123
      responses:
        '200':
          description: Account details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AccountInfo'

  /v1/rms/exchange/{exchange_name}/balances:
    get:
      summary: Get Positions
      description: Returns current holdings with free, used, and total balances for each asset.
      tags:
        - Orders
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
        - name: login
          in: query
          required: true
          schema:
            type: string
          example: acc123
          description: Exchange account login identifier
      responses:
        '200':
          description: Account positions and balances
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AccountInfo'

  /v1/rms/exchange/{exchange_name}/markets:
    get:
      summary: Get Tradable Assets
      description: Returns all markets available for trading on this exchange, including order types and margin info.
      tags:
        - Orders
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
      responses:
        '200':
          description: List of tradable markets
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Market'

  /v1/rms/exchange/{exchange_name}/orders:
    get:
      summary: List Orders
      description: Returns all orders for an account. Optionally filter by trading pair.
      tags:
        - Orders
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
        - name: login
          in: query
          required: true
          schema:
            type: string
          example: acc123
          description: Exchange account login identifier
        - name: symbol
          in: query
          schema:
            type: string
          example: BTC/USDT
          description: Filter by trading pair
      responses:
        '200':
          description: List of orders
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/OrderSummary'

  /v1/rms/exchange/{exchange_name}/transactions:
    get:
      summary: Get Trade History
      description: Returns executed trades for an account, optionally filtered by trading pair.
      tags:
        - Orders
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
        - name: login
          in: query
          required: true
          schema:
            type: string
          example: acc123
        - name: symbol
          in: query
          schema:
            type: string
          example: BTC/USDT
      responses:
        '200':
          description: List of transactions
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Transaction'

  /v1/rms/exchange/{exchange_name}/order/{order_id}:
    delete:
      summary: Cancel Order
      description: Cancels an open order by its ID. Requires the trading pair and account login.
      tags:
        - Orders
      security:
        - BasicAuth: []
      parameters:
        - name: exchange_name
          in: path
          required: true
          schema:
            type: string
          example: binance
        - name: order_id
          in: path
          required: true
          schema:
            type: string
          example: "313075"
        - name: login
          in: query
          required: true
          schema:
            type: string
          example: acc123
        - name: symbol
          in: query
          schema:
            type: string
          example: BTC/USDT
          description: "Trading pair. Can also be passed as a path segment after order_id."
      responses:
        '200':
          description: Cancelled order
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderResponse'
              example:
                amount: 10
                average: 0
                clientOrderId: null
                cost: 0
                datetime: "2026-03-24T10:00:00Z"
                fee:
                  cost: 0
                  currency: null
                fees:
                  - cost: 0
                    currency: null
                filled: 0
                id: "313075"
                info:
                  action: null
                  avgPriceEp: 0
                  baseQtyEv: null
                  bizError: null
                  clOrdID: null
                  cumBaseAmountEv: null
                  cumBaseQtyEv: null
                  cumFeeEv: null
                  cumQuoteAmountEv: null
                  cumQuoteQtyEv: null
                  execInst: null
                  leavesBaseQtyEv: null
                  leavesQuoteQtyEv: null
                  ordStatus: canceled
                  ordType: LMT
                  orderID: "313075"
                  pegOffsetValueEp: null
                  pegPriceType: null
                  priceEp: 0
                  qtyType: null
                  quoteQtyEv: null
                  side: buy
                  stopDirection: null
                  stopPxEp: null
                  symbol: BTC/USDT
                  timeInForce: gtc
                  trigger: null
                lastTradeTimestamp: null
                lastUpdateTimestamp: null
                postOnly: null
                price: 0
                reduceOnly: null
                remaining: 10
                side: buy
                status: canceled
                stopLossPrice: 0
                stopPrice: 0
                symbol: BTC/USDT
                takeProfitPrice: 0
                timeInForce: gtc
                timestamp: null
                trades: []
                triggerPrice: 0
                type: LMT

  # ─── Quotes ────────────────────────────────────────────────────────────
  /v1/quotes/ping:
    get:
      summary: Ping
      description: Quick health check — returns `pong` if the Quotes service is up.
      tags:
        - Quotes
      security:
        - BasicAuth: []
      responses:
        '200':
          description: Service is running
          content:
            application/json:
              schema:
                type: string
              example: pong

  /v1/quotes/ohlcv/latest:
    post:
      summary: Get Latest Quotes
      description: Returns the most recent OHLCV candle for one or more symbols. Auto-routes to the correct data source based on the symbol.
      tags:
        - Quotes
      security:
        - BasicAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - symbols
              properties:
                symbols:
                  type: array
                  items:
                    type: string
                  description: List of ticker symbols (max 500 per request)
            example:
              symbols:
                - AAPL
                - TSLA
      responses:
        '200':
          description: Latest OHLCV data for requested symbols
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/QuoteOHLCV'

  /v1/quotes/ohlcv/history:
    get:
      summary: Get Historical Quotes
      description: Returns historical OHLCV bars for a single symbol. Routes to the correct data source based on exchange prefix.
      tags:
        - Quotes
      security:
        - BasicAuth: []
      parameters:
        - name: symbol
          in: query
          required: true
          schema:
            type: string
          example: AAPL
          description: "Ticker symbol (e.g., AAPL or NSE:RELIANCE)"
        - name: tf
          in: query
          schema:
            type: string
          example: 1d
          description: "Timeframe: 1d, 1h, 1w, 1m. Default: 1d"
        - name: bars
          in: query
          schema:
            type: integer
          example: 200
          description: "Number of bars to return (10-500). Default: 200"
      responses:
        '200':
          description: Historical OHLCV bars
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    timestamp:
                      type: string
                      format: date-time
                    open:
                      type: number
                    high:
                      type: number
                    low:
                      type: number
                    close:
                      type: number
                    volume:
                      type: number
              example:
                - timestamp: "2026-03-20T04:00:00Z"
                  open: 253.97
                  high: 255.18
                  low: 245.83
                  close: 251.68
                  volume: 29662739.0
                - timestamp: "2026-03-21T04:00:00Z"
                  open: 250.10
                  high: 252.50
                  low: 248.00
                  close: 249.85
                  volume: 31200000.0

  # ─── Risk ──────────────────────────────────────────────────────────────
  /v1/rule/ping:
    get:
      summary: Ping
      description: Quick health check — returns a welcome message if the Risk service is up.
      tags:
        - Risk
      security:
        - BasicAuth: []
      responses:
        '200':
          description: Service is running
          content:
            text/plain:
              schema:
                type: string
              example: pong

  /v1/rule/create-rule:
    post:
      summary: Create Rule
      description: Creates a portfolio rule with a condition script. When the condition is met, the rule triggers an alert or auto-places a trade.
      tags:
        - Risk
      security:
        - BasicAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - condition_script
                - user_id
                - account_id
                - exchange
              properties:
                condition_script:
                  type: string
                  description: Script defining the rule condition (e.g., "portfolio.total_value < 10000")
                user_id:
                  type: string
                  description: User identifier
                account_id:
                  type: string
                  description: Account identifier
                exchange:
                  type: string
                  description: Exchange name (e.g., binance)
                symbol:
                  type: string
                  description: "Trading pair. Default: * (account-level)"
                active:
                  type: boolean
                  description: "Whether the rule is active. Default: true"
                rule_name:
                  type: string
                  description: Custom rule name (auto-generated if omitted)
                description:
                  type: string
                  description: Rule description (auto-generated if omitted)
                ruleId:
                  type: string
                  description: Existing rule ID (for updating a rule)
            example:
              condition_script: "portfolio.total_value < 10000"
              user_id: your_user_id
              account_id: your_account_id
              exchange: binance
              symbol: BTC/USDT
              active: true
              rule_name: my_portfolio_rule
              description: Alert when portfolio drops below 10k
      responses:
        '200':
          description: Rule created successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      createMarketRule:
                        type: object
                        properties:
                          marketRule:
                            type: object
                            properties:
                              ruleId:
                                type: string
                              ruleName:
                                type: string
              example:
                data:
                  createMarketRule:
                    marketRule:
                      ruleId: "64c40d41-2616-4a07-9e82-0ae3cac235d6"
                      ruleName: "my_portfolio_rule"

  # ─── Wallet ────────────────────────────────────────────────────────────
  /v1/wallet/ping:
    get:
      summary: Ping
      description: Quick health check — returns `pong` if the Wallet service is up.
      tags:
        - Wallet
      security:
        - BasicAuth: []
      responses:
        '200':
          description: Service is running
          content:
            application/json:
              schema:
                type: string
              example: pong

  /v1/wallet/create-wallet:
    post:
      summary: Create Wallet
      description: Generates a new wallet (address, mnemonic, private key) for the chosen blockchain.
      tags:
        - Wallet
      security:
        - BasicAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - chain
              properties:
                chain:
                  type: string
                  enum:
                    - ETH
                    - BTC
                    - CELO
                    - DOGE
                    - LTC
                    - MATIC
                  description: Blockchain (case-insensitive)
                is_testnet:
                  type: boolean
                  description: "Use testnet if true, mainnet if false. Default: true"
                index:
                  type: integer
                  description: "Derivation index for address/key pair. Default: 0"
            example:
              chain: CELO
              is_testnet: false
              index: 0
      responses:
        '200':
          description: Generated wallet details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WalletInfo'
              example:
                address: "0x123abc..."
                mnemonic: "word1 word2 word3 ..."
                privateKey: "abcdef123456..."
                xpub: "pqrstuv123..."
                chain: celo
                network: mainnet
                index: 0

  /v1/wallet/check-balance:
    get:
      summary: Check Balance
      description: Returns incoming, outgoing, and pending balances for a wallet address.
      tags:
        - Wallet
      security:
        - BasicAuth: []
      parameters:
        - name: chain
          in: query
          required: true
          schema:
            type: string
          example: ETH
          description: Blockchain shorthand (ETH, BTC, MATIC, CELO, LTC, DOGE)
        - name: address
          in: query
          required: true
          schema:
            type: string
          example: "0x0000000000000000000000000000000000000000"
        - name: network
          in: query
          schema:
            type: string
            enum:
              - testnet
              - mainnet
          example: testnet
          description: "Default: testnet"
      responses:
        '200':
          description: Wallet balance
          content:
            application/json:
              schema:
                type: object
                properties:
                  chain:
                    type: string
                  network:
                    type: string
                  address:
                    type: string
                  balance:
                    type: object
                    properties:
                      balance:
                        type: string
              example:
                chain: eth
                network: testnet
                address: "0x0000000000000000000000000000000000000000"
                balance:
                  balance: "131783.371298885164867059"

  /v1/wallet/send-transaction:
    post:
      summary: Send Transaction
      description: Signs and broadcasts a transfer from one wallet to another. The private key is used locally for signing only.
      tags:
        - Wallet
      security:
        - BasicAuth: []
      parameters:
        - name: chain
          in: query
          required: true
          schema:
            type: string
          example: ETH
        - name: testnet
          in: query
          schema:
            type: string
          example: "true"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - to
                - amount
                - from_private_key
              properties:
                to:
                  type: string
                  description: Destination wallet address
                amount:
                  type: string
                  description: Amount to send
                from_private_key:
                  type: string
                  description: Sender's private key (used only for local signing)
            example:
              to: "0x123abc456def..."
              amount: "0.001"
              from_private_key: "your_private_key"
      responses:
        '200':
          description: Transaction broadcast result
          content:
            application/json:
              schema:
                type: object
                properties:
                  txId:
                    type: string
                  status:
                    type: string
              example:
                txId: "0xabc123def456..."
                status: broadcasted

  /v1/wallet/transactions:
    get:
      summary: Transaction History
      description: Returns past transactions for a wallet address with pagination and time-range filters.
      tags:
        - Wallet
      security:
        - BasicAuth: []
      parameters:
        - name: chain
          in: query
          required: true
          schema:
            type: string
          example: BTC
        - name: address
          in: query
          required: true
          schema:
            type: string
          example: "tb1qxxxxxxxyyyzzz111222abc"
        - name: network
          in: query
          schema:
            type: string
            enum:
              - testnet
              - mainnet
          example: testnet
        - name: pageSize
          in: query
          required: true
          schema:
            type: integer
          example: 10
        - name: offset
          in: query
          schema:
            type: integer
          example: 0
        - name: from
          in: query
          schema:
            type: integer
            format: int64
          description: Start time filter (timestamp in ms)
        - name: to
          in: query
          schema:
            type: integer
            format: int64
          description: End time filter (timestamp in ms)
        - name: sort
          in: query
          schema:
            type: string
            enum:
              - ASC
              - DESC
          example: DESC
      responses:
        '200':
          description: Transaction history
          content:
            application/json:
              schema:
                type: object
                properties:
                  chain:
                    type: string
                  network:
                    type: string
                  address:
                    type: string
                  transactions:
                    type: array
                    items:
                      $ref: '#/components/schemas/BlockchainTransaction'


# ─── Components ────────────────────────────────────────────────────────
components:
  securitySchemes:
    BasicAuth:
      type: http
      scheme: basic

  schemas:
    PingResponse:
      type: object
      properties:
        success:
          type: string
      example:
        success: pong

    Market:
      type: object
      properties:
        base:
          type: string
        exchange:
          type: string
        id:
          type: string
        info:
          type: object
        limits:
          type: object
          properties:
            amount:
              type: object
              properties:
                max:
                  type: number
                min:
                  type: number
            cost:
              type: object
              properties:
                max:
                  type: number
                min:
                  type: number
            leverage:
              type: object
              properties:
                max:
                  type: number
                  nullable: true
                min:
                  type: number
                  nullable: true
            price:
              type: object
              properties:
                max:
                  type: number
                  nullable: true
                min:
                  type: number
                  nullable: true
        precision:
          type: object
          properties:
            amount:
              type: number
            base:
              type: number
              nullable: true
            cost:
              type: number
              nullable: true
            price:
              type: number
            quote:
              type: number
              nullable: true
        quote:
          type: string
        symbol:
          type: string

    Currency:
      type: object
      properties:
        active:
          type: boolean
        code:
          type: string
        deposit:
          type: boolean
        fee:
          type: number
          nullable: true
        id:
          type: string
        info:
          type: object
        limits:
          type: object
          properties:
            amount:
              type: object
              properties:
                max:
                  type: number
                  nullable: true
                min:
                  type: number
                  nullable: true
            deposit:
              type: object
              properties:
                max:
                  type: number
                  nullable: true
                min:
                  type: number
            withdraw:
              type: object
              properties:
                max:
                  type: number
                min:
                  type: number
        name:
          type: string
        networks:
          type: object
        precision:
          type: number
        type:
          type: string
        withdraw:
          type: boolean

    Ticker:
      type: object
      properties:
        ask:
          type: number
          nullable: true
        askVolume:
          type: number
          nullable: true
        average:
          type: number
          nullable: true
        baseVolume:
          type: number
          nullable: true
        bid:
          type: number
          nullable: true
        bidVolume:
          type: number
          nullable: true
        change:
          type: number
          nullable: true
        close:
          type: number
          nullable: true
        datetime:
          type: string
          nullable: true
        high:
          type: number
          nullable: true
        indexPrice:
          type: number
          nullable: true
        info:
          type: object
        last:
          type: number
          nullable: true
        low:
          type: number
          nullable: true
        markPrice:
          type: number
          nullable: true
        open:
          type: number
          nullable: true
        percentage:
          type: number
          nullable: true
        previousClose:
          type: number
          nullable: true
        quoteVolume:
          type: number
          nullable: true
        symbol:
          type: string
        timestamp:
          type: integer
          nullable: true
        vwap:
          type: number
          nullable: true

    Candle:
      type: object
      properties:
        open:
          type: number
        high:
          type: number
        low:
          type: number
        close:
          type: number
        volume:
          type: number
        datetime:
          type: integer
          format: int64
          description: Timestamp in milliseconds since epoch

    Rate:
      type: object
      properties:
        currencySymbol:
          type: string
        id:
          type: string
        rateUsd:
          type: number
        symbol:
          type: string
        type:
          type: string
          enum:
            - fiat
            - crypto

    NewsArticle:
      type: object
      properties:
        description:
          type: string
        link:
          type: string
        published_at:
          type: string
          format: date-time
        source:
          type: string
        symbol:
          type: string
        title:
          type: string

    OrderResponse:
      type: object
      description: Full order execution result from the exchange
      properties:
        id:
          type: string
        amount:
          type: number
        average:
          type: number
        clientOrderId:
          type: string
        cost:
          type: number
        datetime:
          type: string
          format: date-time
        fee:
          type: object
          properties:
            cost:
              type: number
            currency:
              type: string
        filled:
          type: number
        info:
          type: object
          description: Raw exchange-specific response data
        price:
          type: number
        remaining:
          type: number
        side:
          type: string
          enum:
            - buy
            - sell
        status:
          type: string
          description: "Order status. Cancel order returns 'canceled'."
          enum:
            - open
            - closed
            - canceled
            - canceling
            - rejected
            - expired
        symbol:
          type: string
        timestamp:
          type: integer
          format: int64
        type:
          type: string
          enum:
            - market
            - limit
            - stop
        trades:
          type: array
          items:
            type: object
            properties:
              amount:
                type: number
              cost:
                type: number
              price:
                type: number
              id:
                type: string

    OrderSummary:
      type: object
      properties:
        id:
          type: string
        symbol:
          type: string
        type:
          type: string
        side:
          type: string
        status:
          type: string
        price:
          type: number
        amount:
          type: number
        filled:
          type: number
        remaining:
          type: number
        cost:
          type: number
        fee:
          type: number
        commission:
          type: number
        datetime:
          type: string
          format: date-time
        info:
          type: object

    Transaction:
      type: object
      properties:
        id:
          type: string
        symbol:
          type: string
        type:
          type: string
        side:
          type: string
        status:
          type: string
        price:
          type: number
        amount:
          type: number
        cost:
          type: number
        filled:
          type: number
        remaining:
          type: number
        fee:
          type: number
        commission:
          type: string
        datetime:
          type: string
        timestamp:
          type: integer
          format: int64
        info:
          type: object

    AccountInfo:
      type: object
      properties:
        balances:
          type: array
          items:
            type: object
            properties:
              currency:
                type: string
              free:
                type: number
              total:
                type: number
              used:
                type: number
        info:
          type: object
          properties:
            accountType:
              type: string
            balances:
              type: array
              items:
                type: object
                properties:
                  asset:
                    type: string
                  free:
                    type: string
                  locked:
                    type: string
            canDeposit:
              type: boolean
            canTrade:
              type: boolean
            canWithdraw:
              type: boolean
            commissionRates:
              type: object
              properties:
                buyer:
                  type: string
                maker:
                  type: string
                seller:
                  type: string
                taker:
                  type: string
            permissions:
              type: array
              items:
                type: string
            uid:
              type: string

    QuoteOHLCV:
      type: object
      properties:
        symbol:
          type: string
        timestamp:
          type: string
          format: date-time
        open:
          type: number
        high:
          type: number
        low:
          type: number
        close:
          type: number
        volume:
          type: number
        last:
          type: number
        bidPrice:
          type: number
        askPrice:
          type: number
        bidSize:
          type: number
        askSize:
          type: number
        netChange:
          type: number
        changePercent:
          type: number
        fiftyTwoHigh:
          type: number
          nullable: true
        fiftyTwoLow:
          type: number
          nullable: true

    WalletInfo:
      type: object
      properties:
        address:
          type: string
        mnemonic:
          type: string
        privateKey:
          type: string
        xpub:
          type: string
        chain:
          type: string
        network:
          type: string
        index:
          type: integer

    BlockchainTransaction:
      type: object
      description: Transaction details (structure varies by chain — this shows the ETH format)
      properties:
        transactionHash:
          type: string
        blockHash:
          type: string
        blockNumber:
          type: integer
        from:
          type: string
        gas:
          type: integer
        gasPrice:
          type: string
        maxPriorityFeePerGas:
          type: integer
          nullable: true
        maxFeePerGas:
          type: integer
          nullable: true
        input:
          type: string
        nonce:
          type: integer
        to:
          type: string
        transactionIndex:
          type: integer
        value:
          type: string
        type:
          type: integer
        chainId:
          type: integer
        contractAddress:
          type: string
          nullable: true
        cumulativeGasUsed:
          type: integer
        effectiveGasPrice:
          type: integer
        gasUsed:
          type: integer
        status:
          type: boolean
        hash:
          type: string
        timestamp:
          type: integer
          format: int64

security:
  - BasicAuth: []
