Exemplos de Integração
curl
Sinais do scan
curl -s https://api.quantfx.com.br/api/scan \
-H "X-API-Key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \
| jq '.items[] | {symbol, timeframe, signal, confidence}'
Status do EA
curl -s https://api.quantfx.com.br/api/ea-status \
-H "X-API-Key: xxxxxxxx-..." \
| jq '.online, .last_heartbeat'
Histórico de 7 dias
curl -s 'https://api.quantfx.com.br/api/account/signals?days=7&limit=100' \
-H "X-API-Key: xxxxxxxx-..." \
| jq '.signals[] | [.created_at, .symbol, .signal, .confidence] | @csv'
Saúde da API
curl -sw "\n%{http_code}\n" https://api.quantfx.com.br/api/health
Python
Cliente básico
import os
import requests
API_URL = "https://api.quantfx.com.br"
API_KEY = os.environ["QUANTFX_KEY"] # nunca hardcode
session = requests.Session()
session.headers.update({"X-API-Key": API_KEY})
def get_scan(min_confidence: float = 0.0) -> list[dict]:
r = session.get(f"{API_URL}/api/scan", params={"min_confidence": min_confidence}, timeout=30)
r.raise_for_status()
return r.json()["items"]
def get_account_signals(days: int = 7, limit: int = 50) -> list[dict]:
r = session.get(
f"{API_URL}/api/account/signals",
params={"days": days, "limit": limit},
timeout=30,
)
r.raise_for_status()
return r.json()["signals"]
def post_execution(payload: dict) -> dict:
r = session.post(f"{API_URL}/api/executions", json=payload, timeout=10)
r.raise_for_status()
return r.json()
# Uso
if __name__ == "__main__":
sinais = get_scan(min_confidence=0.55)
for s in sinais:
if s["signal"] != "NO_TRADE":
print(f"{s['symbol']} {s['timeframe']}: {s['signal']} ({s['confidence']:.0%})")
import time
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(
total=5,
backoff_factor=1, # 1s, 2s, 4s, 8s, 16s
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET", "POST"],
)
session.mount("https://", HTTPAdapter(max_retries=retry))
Async (httpx)
import httpx
import asyncio
async def get_signals_async():
async with httpx.AsyncClient(
base_url="https://api.quantfx.com.br",
headers={"X-API-Key": API_KEY},
timeout=30,
) as client:
r = await client.get("/api/account/signals", params={"days": 7})
r.raise_for_status()
return r.json()
asyncio.run(get_signals_async())
JavaScript / TypeScript
Browser (fetch)
const API_KEY = sessionStorage.getItem('quantfx_key');
async function fetchSignals(days = 7) {
const r = await fetch(`/api/account/signals?days=${days}&limit=50`, {
headers: { 'X-API-Key': API_KEY }
});
if (r.status === 401) throw new Error('Chave inválida');
if (!r.ok) throw new Error('HTTP ' + r.status);
return r.json();
}
const data = await fetchSignals(7);
console.log(data.count, 'sinais');
Node.js (axios)
const axios = require('axios');
const client = axios.create({
baseURL: 'https://api.quantfx.com.br',
headers: { 'X-API-Key': process.env.QUANTFX_KEY },
timeout: 30000,
});
async function regenerate() {
const { data } = await client.post('/api/account/regenerate-key');
console.log('Nova key:', data.api_key);
return data.api_key;
}
regenerate();
MQL5 (Expert Advisor)
WebRequest síncrono
string ScanAPI() {
string headers = "X-API-Key: " + InpApiKey + "\r\n";
char post[], response[];
string response_headers;
ResetLastError();
int status = WebRequest("GET",
InpApiUrl + "/api/scan?min_confidence=0",
headers,
5000, // timeout ms
post, // sem body
response,
response_headers);
if (status == -1) {
int err = GetLastError();
PrintFormat("WebRequest fail: %d (verifique se URL está liberada em Ferramentas → Opções → Expert Advisors)", err);
return "";
}
if (status != 200) {
PrintFormat("HTTP %d: %s", status, CharArrayToString(response));
return "";
}
return CharArrayToString(response);
}
Reportar execution
void ReportExecution(long ticket, string symbol, string tf, string sig,
double conf, datetime opened, datetime closed,
double entry, double exit, double pnl, string result) {
string body = StringFormat(
"{\"ticket\":%I64d,\"symbol\":\"%s\",\"timeframe\":\"%s\","
"\"signal\":\"%s\",\"confidence\":%.4f,"
"\"opened_at\":\"%s\",\"closed_at\":\"%s\","
"\"entry_price\":%.5f,\"exit_price\":%.5f,"
"\"pnl\":%.2f,\"result\":\"%s\"}",
ticket, symbol, tf, sig, conf,
TimeToString(opened, TIME_DATE | TIME_SECONDS),
TimeToString(closed, TIME_DATE | TIME_SECONDS),
entry, exit, pnl, result);
string headers = "X-API-Key: " + InpApiKey + "\r\n" +
"Content-Type: application/json\r\n";
char post[], response[];
string response_headers;
StringToCharArray(body, post, 0, StringLen(body));
int status = WebRequest("POST",
InpApiUrl + "/api/executions",
headers, 5000, post, response, response_headers);
PrintFormat("Reported exec: HTTP %d", status);
}
Python para análise estatística
import pandas as pd
import requests
# Pegar 30 dias de operações
r = requests.get(
"https://api.quantfx.com.br/api/account/executions?days=30&limit=1000",
headers={"X-API-Key": API_KEY},
)
data = r.json()
df = pd.DataFrame(data["executions"])
# Métricas
print(df.describe())
print("Win rate:", (df["pnl"] > 0).mean())
print("Sharpe (daily):", df.groupby(df["closed_at"].str[:10])["pnl"].sum().describe())
# Por símbolo
by_symbol = df.groupby("symbol").agg(
n=("exec_id", "count"),
pnl=("pnl", "sum"),
wr=("pnl", lambda x: (x > 0).mean()),
)
print(by_symbol.sort_values("pnl", ascending=False))
Postman
- Import collection do OpenAPI:
https://api.quantfx.com.br/openapi.json
- Em "Authorization" do collection:
- Type: API Key
- Key:
X-API-Key
- Value:
{{api_key}} (variable do environment)
- Adicionar environment com:
base_url = https://api.quantfx.com.br
api_key = sua chave UUID
Limites de uso por plano
| Operação |
Frequência típica |
Plano mínimo |
/api/scan em loop |
1× por minuto |
Basic |
/api/scan em loop por slot |
14 × por minuto |
Pro (300/min limit) |
Dashboard /minha-conta aberto |
5 reqs em open + reload manual |
Basic |
| Scripts de análise (batch) |
50 reqs em rajada |
Owner ou Pro |
| EA + frontend simultâneos |
~60 reqs/min |
Pro |