MQuant Developers v1
Open MQuant

Code examples

Three complete clients, one per language, each signing exactly as the server checks. Copy one into your project, or download it, and set MQ_API_KEY and MQ_API_SECRET.

Each client is tested against the MQuant API server code: GET /me, POST /signals/test, and sending, looking up and cancelling a signal. Run one directly and it syncs the clock, calls GET /api/v1/me and dry-runs a signal. Nothing is stored.

LanguageFileNeeds
Pythonmquant_signals.pyPython 3.9+, requests
Node.jsmquant-signals.mjsNode.js 18+, no packages
Shellmq.shbash, curl, openssl

Python#

Python 3.9 or later with requests (pip install requests). Save as mquant_signals.py, or download it.

mquant_signals.py
import hashlib
import hmac
import json
import os
import random
import time
import uuid
from urllib.parse import quote, urlencode

import requests

BASE_URL = "https://app.mquant.in"


class MQuantError(Exception):
    def __init__(self, status, body, retry_after=None):
        self.status = status
        self.body = body if isinstance(body, dict) else {}
        self.code = self.body.get("code")
        self.details = self.body.get("details", [])
        self.request_id = self.body.get("request_id")
        self.retry_after = int(retry_after) if retry_after else 0
        super().__init__(f"{status} {self.code}: {self.body.get('message')} (request_id {self.request_id})")


class MQuantClient:
    def __init__(self, key_id, secret, base_url=BASE_URL, timeout=10):
        self.key_id = key_id
        self.secret = secret.encode("ascii")
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.clock_offset_ms = 0
        self.session = requests.Session()
        self.last_response = None

    def sync_clock(self):
        started = time.time() * 1000
        reply = self.session.get(self.base_url + "/api/v1/time", timeout=self.timeout)
        finished = time.time() * 1000
        if reply.status_code != 200:
            raise MQuantError(reply.status_code, reply.json(), reply.headers.get("Retry-After"))
        server_ms = reply.json()["data"]["server_time_ms"]
        self.clock_offset_ms = int(server_ms - (started + finished) / 2)
        return self.clock_offset_ms

    def _signed_headers(self, method, target, body):
        timestamp = str(int(time.time() * 1000) + self.clock_offset_ms)
        nonce = str(uuid.uuid4())
        body_hash = hashlib.sha256(body).hexdigest()
        canonical = "\n".join([method, target, timestamp, nonce, self.key_id, body_hash])
        signature = hmac.new(self.secret, canonical.encode("ascii"), hashlib.sha256).hexdigest()
        return {
            "X-MQ-API-KEY": self.key_id,
            "X-MQ-TIMESTAMP": timestamp,
            "X-MQ-NONCE": nonce,
            "X-MQ-SIGNATURE": signature,
        }

    def request(self, method, path, params=None, payload=None):
        target = path + ("?" + urlencode(params) if params else "")
        body = b"" if payload is None else json.dumps(payload, separators=(",", ":")).encode("utf-8")
        headers = self._signed_headers(method, target, body)
        if body:
            headers["Content-Type"] = "application/json"
        reply = self.session.request(method, self.base_url + target, data=body or None,
                                     headers=headers, timeout=self.timeout)
        self.last_response = reply
        data = reply.json()
        if reply.status_code >= 400:
            raise MQuantError(reply.status_code, data, reply.headers.get("Retry-After"))
        return data["data"]

    def get(self, path, params=None):
        return self.request("GET", path, params=params)

    def post(self, path, payload=None):
        return self.request("POST", path, payload=payload)

    def signal(self, signal_id):
        return self.get("/api/v1/signals/" + signal_id)

    def signal_by_client_id(self, client_signal_id):
        return self.get("/api/v1/signals/by-client-id/" + quote(client_signal_id, safe=""))

    def cancel(self, signal_id, reason=None):
        return self.post("/api/v1/signals/" + signal_id + "/cancel", {"reason": reason} if reason else None)

    def send_signal(self, signal, attempts=4):
        for attempt in range(1, attempts + 1):
            try:
                return self.post("/api/v1/signals", signal)
            except MQuantError as error:
                retryable = error.status >= 500 or (error.status == 429 and error.retry_after <= 60)
                if attempt == attempts or not retryable:
                    raise
                wait = error.retry_after if error.status == 429 else self._backoff(attempt)
            except requests.RequestException:
                if attempt == attempts:
                    raise
                wait = self._backoff(attempt)
            time.sleep(wait)

    @staticmethod
    def _backoff(attempt):
        return min(30.0, 0.5 * 2 ** (attempt - 1)) * random.uniform(0.5, 1.0)


if __name__ == "__main__":
    mq = MQuantClient(os.environ["MQ_API_KEY"], os.environ["MQ_API_SECRET"])
    print("clock offset ms:", mq.sync_clock())

    me = mq.get("/api/v1/me")
    print("key:", me["key_id"], "mode:", me["mode"], "caller_ip:", me["caller_ip"])

    check = mq.post("/api/v1/signals/test", {
        "client_signal_id": "reliance-0001",
        "exchange": "NSE",
        "symbol": "RELIANCE",
        "instrument_type": "EQ",
        "side": "BUY",
        "quantity": 10,
        "order_type": "LIMIT",
        "price": "1250.50",
        "product": "CNC",
    })
    print("valid:", check["valid"], "warnings:", check["warnings"])

Use it from your own code:

Your code
import os

from mquant_signals import MQuantClient, MQuantError

mq = MQuantClient(os.environ["MQ_API_KEY"], os.environ["MQ_API_SECRET"])
mq.sync_clock()

try:
    signal = mq.send_signal({
        "client_signal_id": "infy-0003",
        "exchange": "NSE",
        "symbol": "INFY",
        "instrument_type": "EQ",
        "side": "SELL",
        "quantity": 25,
        "order_type": "MARKET",
        "product": "MIS",
    })
    print(signal["signal_id"], signal["status"], "replayed" if signal["replayed"] else "new")
except MQuantError as error:
    print(error.status, error.code, error.details, error.request_id)

Node.js#

Node.js 18 or later. No packages: it uses the built-in crypto and fetch. Save as mquant-signals.mjs, or download it.

mquant-signals.mjs
import crypto from 'node:crypto'
import { pathToFileURL } from 'node:url'

const BASE_URL = 'https://app.mquant.in'

export class MQuantError extends Error {
  constructor(status, body, retryAfter) {
    const info = body && typeof body === 'object' ? body : {}
    super(`${status} ${info.code}: ${info.message} (request_id ${info.request_id})`)
    this.status = status
    this.body = info
    this.code = info.code
    this.details = info.details ?? []
    this.requestId = info.request_id
    this.retryAfter = retryAfter ? Number(retryAfter) : 0
  }
}

export class MQuantClient {
  constructor(keyId, secret, { baseUrl = BASE_URL, timeoutMs = 10000 } = {}) {
    this.keyId = keyId
    this.secret = secret
    this.baseUrl = baseUrl.replace(/\/+$/, '')
    this.timeoutMs = timeoutMs
    this.clockOffsetMs = 0
    this.lastStatus = null
  }

  async syncClock() {
    const started = Date.now()
    const response = await fetch(this.baseUrl + '/api/v1/time', { signal: AbortSignal.timeout(this.timeoutMs) })
    const finished = Date.now()
    const body = await response.json()
    if (response.status !== 200) throw new MQuantError(response.status, body, response.headers.get('retry-after'))
    this.clockOffsetMs = Math.round(body.data.server_time_ms - (started + finished) / 2)
    return this.clockOffsetMs
  }

  signedHeaders(method, target, body) {
    const timestamp = String(Date.now() + this.clockOffsetMs)
    const nonce = crypto.randomUUID()
    const bodyHash = crypto.createHash('sha256').update(body, 'utf8').digest('hex')
    const canonical = [method, target, timestamp, nonce, this.keyId, bodyHash].join('\n')
    const signature = crypto.createHmac('sha256', this.secret).update(canonical, 'utf8').digest('hex')
    return {
      'X-MQ-API-KEY': this.keyId,
      'X-MQ-TIMESTAMP': timestamp,
      'X-MQ-NONCE': nonce,
      'X-MQ-SIGNATURE': signature,
    }
  }

  async request(method, path, { params, payload } = {}) {
    const query = params ? new URLSearchParams(params).toString() : ''
    const target = path + (query ? '?' + query : '')
    const body = payload === undefined ? '' : JSON.stringify(payload)
    const headers = this.signedHeaders(method, target, body)
    if (body) headers['Content-Type'] = 'application/json'
    const response = await fetch(this.baseUrl + target, {
      method,
      headers,
      body: body || undefined,
      signal: AbortSignal.timeout(this.timeoutMs),
    })
    this.lastStatus = response.status
    const data = await response.json()
    if (response.status >= 400) throw new MQuantError(response.status, data, response.headers.get('retry-after'))
    return data.data
  }

  get(path, params) {
    return this.request('GET', path, { params })
  }

  post(path, payload) {
    return this.request('POST', path, { payload })
  }

  signal(signalId) {
    return this.get('/api/v1/signals/' + signalId)
  }

  signalByClientId(clientSignalId) {
    return this.get('/api/v1/signals/by-client-id/' + encodeURIComponent(clientSignalId))
  }

  cancel(signalId, reason) {
    return this.post('/api/v1/signals/' + signalId + '/cancel', reason ? { reason } : undefined)
  }

  async sendSignal(signal, attempts = 4) {
    for (let attempt = 1; ; attempt++) {
      let wait
      try {
        return await this.post('/api/v1/signals', signal)
      } catch (error) {
        const status = error instanceof MQuantError ? error.status : 0
        const retryable = status === 0 || status >= 500 || (status === 429 && error.retryAfter <= 60)
        if (attempt >= attempts || !retryable) throw error
        wait = status === 429 ? error.retryAfter * 1000 : backoffMs(attempt)
      }
      await new Promise((resolve) => setTimeout(resolve, wait))
    }
  }
}

function backoffMs(attempt) {
  return Math.min(30000, 500 * 2 ** (attempt - 1)) * (0.5 + Math.random() / 2)
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const mq = new MQuantClient(process.env.MQ_API_KEY, process.env.MQ_API_SECRET)
  console.log('clock offset ms:', await mq.syncClock())

  const me = await mq.get('/api/v1/me')
  console.log('key:', me.key_id, 'mode:', me.mode, 'caller_ip:', me.caller_ip)

  const check = await mq.post('/api/v1/signals/test', {
    client_signal_id: 'reliance-0001',
    exchange: 'NSE',
    symbol: 'RELIANCE',
    instrument_type: 'EQ',
    side: 'BUY',
    quantity: 10,
    order_type: 'LIMIT',
    price: '1250.50',
    product: 'CNC',
  })
  console.log('valid:', check.valid, 'warnings:', check.warnings)
}
Your code (an .mjs file)
import { MQuantClient, MQuantError } from './mquant-signals.mjs'

const mq = new MQuantClient(process.env.MQ_API_KEY, process.env.MQ_API_SECRET)
await mq.syncClock()

try {
  const signal = await mq.sendSignal({
    client_signal_id: 'infy-0003',
    exchange: 'NSE',
    symbol: 'INFY',
    instrument_type: 'EQ',
    side: 'SELL',
    quantity: 25,
    order_type: 'MARKET',
    product: 'MIS',
  })
  console.log(signal.signal_id, signal.status, signal.replayed ? 'replayed' : 'new')
} catch (error) {
  if (!(error instanceof MQuantError)) throw error
  console.log(error.status, error.code, error.details, error.requestId)
}

Shell (curl and openssl)#

Bash with curl and openssl, for checks by hand and quick scripts. It works on Linux and macOS. Save as mq.sh and run chmod +x mq.sh, or download it.

mq.sh
#!/usr/bin/env bash
set -euo pipefail

BASE_URL="https://app.mquant.in"

if [ $# -lt 2 ]; then
  echo "usage: $0 METHOD PATH_WITH_QUERY [JSON_BODY]" >&2
  exit 64
fi

METHOD="$1"
TARGET="$2"
BODY="${3-}"
: "${MQ_API_KEY:?set MQ_API_KEY}"
: "${MQ_API_SECRET:?set MQ_API_SECRET}"

now_ms() {
  local ms
  ms=$(date +%s%3N)
  case "$ms" in
    *N) echo $(( $(date +%s) * 1000 )) ;;
    *) echo "$ms" ;;
  esac
}

TS=$(now_ms)
NONCE=$(openssl rand -hex 16)
BODY_HASH=$(printf '%s' "$BODY" | openssl dgst -sha256 | awk '{print $NF}')
SIGNATURE=$(printf '%s\n%s\n%s\n%s\n%s\n%s' "$METHOD" "$TARGET" "$TS" "$NONCE" "$MQ_API_KEY" "$BODY_HASH" \
  | openssl dgst -sha256 -hmac "$MQ_API_SECRET" | awk '{print $NF}')

ARGS=(-sS -X "$METHOD" "$BASE_URL$TARGET"
  -H "X-MQ-API-KEY: $MQ_API_KEY"
  -H "X-MQ-TIMESTAMP: $TS"
  -H "X-MQ-NONCE: $NONCE"
  -H "X-MQ-SIGNATURE: $SIGNATURE"
  -w '\nHTTP %{http_code}\n')
if [ -n "$BODY" ]; then
  ARGS+=(-H "Content-Type: application/json" --data-binary "$BODY")
fi

curl "${ARGS[@]}"
Usage
./mq.sh GET /api/v1/me
./mq.sh GET '/api/v1/signals?status=received&limit=5'
./mq.sh POST /api/v1/signals/test '{"client_signal_id":"reliance-0001","exchange":"NSE","symbol":"RELIANCE","instrument_type":"EQ","side":"BUY","quantity":10,"order_type":"LIMIT","price":"1250.50","product":"CNC"}'
Keep the shell client on your own machine

openssl -hmac receives the secret as a command-line argument, which other users of the same machine can see in the process list while it runs. Use mq.sh on a machine only you use, and the Python or Node client in production. Always quote the query string in the shell, because & is special.

Writing your own client#

Writing a client in another language? It must do exactly this, and nothing more:

  1. Serialise the body once to UTF-8 bytes. For GET and a cancel without a reason, the body is empty.
  2. Build the request target: the path from /api/v1, plus ? and the encoded query string if there is one.
  3. Take the time in milliseconds (corrected by your measured offset), and a new random nonce.
  4. Join method, target, timestamp, nonce, key id and the hex SHA-256 of the body with \n, and HMAC-SHA256 it with the secret.
  5. Send the same bytes to the same target with the four X-MQ- headers, plus Content-Type: application/json when there is a body.

Then reproduce the worked example in your test suite, so a library upgrade can never silently change your signing.

MQuant is the platform of Sykes & Ray Equities. Questions go to your MQuant desk contact.