Skip to content

📈 Get real-time stocks from TradingView

Add interactive npx quick-start with agent setup paths (#341)

Mathieu Colmon7124bd0f48d5
diff --git a/README.md b/README.md
index 81bce26..7c93ac7 100644
--- a/README.md
+++ b/README.md
@@ -8,13 +8,15 @@
[![Tests](https://github.com/Mathieu2301/TradingView-API/actions/workflows/tests.yml/badge.svg?branch=main)](https://github.com/Mathieu2301/TradingView-API/actions/workflows/tests.yml) [![npm](https://badgen.net/npm/v/@mathieuc/tradingview)](https://www.npmjs.com/package/@mathieuc/tradingview) [![Stars](https://img.shields.io/github/stars/Mathieu2301/TradingView-API?style=social)](https://github.com/Mathieu2301/TradingView-API)
+<a href="https://trendshift.io/repositories/26416?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-26416" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/26416" alt="Mathieu2301/TradingView-API | #1 Repo Of The Day on Trendshift" width="250" height="55"/></a>
+
![Recorded demonstration: a candle request returns 40 daily BTC/USDT candles, visualized as a line chart](assets/readme-demo.gif)
*An actual candle request, recorded on 2 October 2026 with the development preview (`fetchCandles`, called `getCandles` in version 4) and visualized for this demo. Prices are not live.*
### One request, real data
-> **V4 beta is currently available from this repository, not from npm.** Build the source as shown below before running this example. The latest npm release is still v3 and does not export `getCandles`.
+> **V4 release candidate is available on npm under `next`.** Install with `npm install @mathieuc/tradingview@next`. The default `latest` tag is still v3 and does not export `getCandles`.
```js
import { getCandles } from '@mathieuc/tradingview/data';
@@ -29,31 +31,40 @@ Prefer to start without code? The setup paths below work too.
## Get started
-### 1. Molted.cloud — recommended, no local setup
-
-[Create an agent on Molted.cloud](https://molted.cloud/) and share this repository with it. Describe what you want to build; the agent can read the docs, set up a workspace, and help you get from an idea to a working project. For example, ask it to build a market-data watcher with this library. [See an example on Molted Studio](https://molted.studio/dreams/market-watch-alerts).
+### Interactive quick-start
-### 2. Claude Code, Codex, or another coding assistant
+<!-- The launcher is introduced after 4.0.0-rc.0; keep this explicit until published. -->
+The next package release adds this interactive launcher (not included in RC.0):
-Open your project in your preferred coding assistant and give it the [repository link](https://github.com/Mathieu2301/TradingView-API). You can start with:
+```bash
+npx @mathieuc/tradingview@next
+```
-> Read the TradingView-API README and the data API guide. Build the V4 beta from source, make a small example that fetches candles and watches a quote, and show me how to run it.
+Run it from your project directory with Node.js 20+. Choose a path:
-The assistant can handle the setup, but you keep the project in your own environment.
+1. **Autonomous agent (recommended)** — opens the [TradingView-API market watcher on Molted Studio](https://molted.studio/dreams/market-watch-alerts). No local project setup.
+2. **Claude Code CLI** — starts your installed `claude` CLI here with a ready-to-use project prompt.
+3. **Codex CLI** — starts your installed `codex` CLI here with the same prompt.
+4. **Another local coding agent** — prints the prompt to paste into your agent.
+5. **Install the library only** — runs `npm install @mathieuc/tradingview@next` here, without generating files or starting an agent.
-### 3. Install manually
+Claude Code and Codex must already be installed and authenticated. Their normal permission prompts remain enabled. If launch fails, the prompt is printed for manual use. If no browser is available, the hosted link remains visible.
-The V4 beta requires Node.js 20 or later, or Bun. **Until the V4 npm release, install it from source:**
+Use `--choice 4` to print the prompt directly, or `--help` for usage. Non-interactive callers must pass `--choice`. To try the launcher from this checkout before publication:
```bash
-git clone https://github.com/Mathieu2301/TradingView-API.git
-cd TradingView-API
npm ci && npm run build
-node examples/candles.js
-# Or use Bun: bun install && bun run build && bun examples/candles.js
+node bin/tradingview.mjs
+```
+
+### Install manually
+
+```bash
+npm install @mathieuc/tradingview@next
+# Or: bun add @mathieuc/tradingview@next
```
-Inside this built checkout, the examples and package self-imports use the V4 API. Running `npm install @mathieuc/tradingview` or `bun add @mathieuc/tradingview` in another project currently installs **v3**, which has the old `Client` API. Do not copy the V4 imports into a project that has v3 installed.
+`next` installs the V4 release candidate; the default `latest` tag still installs V3. Do not mix the V4 imports with a V3 installation.
The V4 package is ESM with TypeScript declarations. CommonJS projects can `require()` it on Node 20.19+ or 22.12+, or use `await import()`.
diff --git a/bin/tradingview.mjs b/bin/tradingview.mjs
new file mode 100755
index 0000000..d2ffc47
--- /dev/null
+++ b/bin/tradingview.mjs
@@ -0,0 +1,7 @@
+#!/usr/bin/env node
+import { main } from '../dist/quick-start.js';
+
+main().then((code) => { process.exitCode = code; }).catch((error) => {
+ console.error(`Quick-start failed: ${error.message}`);
+ process.exitCode = 1;
+});
diff --git a/docs/README.es.md b/docs/README.es.md
index 670ac4a..8ba4679 100644
--- a/docs/README.es.md
+++ b/docs/README.es.md
@@ -1,58 +1,150 @@
# TradingView-API
-**Pruébalo con un agente alojado:** [Crea un vigilante de mercado en Molted Studio](https://molted.studio/dreams/market-watch-alerts) — sin instalación local.
+**Construye con datos de mercado, desde tu primer gráfico hasta un monitor en funcionamiento.** Obtén velas y cotizaciones, ejecuta indicadores y estrategias, y convierte tus ideas en herramientas. Un proyecto comunitario independiente, no una API oficial de TradingView.
-<a href="https://trendshift.io/repositories/26416?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-26416" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/26416" alt="Mathieu2301/TradingView-API | #1 Repo Of The Day on Trendshift" width="250" height="55"/></a>
+[Primeros pasos](#primeros-pasos) · [Explorar ejemplos](../examples) · [Leer la guía de la API de datos](data-api.md)
**Idioma:** [English](../README.md) · [Français](README.fr.md) · Español · [Português](README.pt.md)
-**Datos de mercado e indicadores para construir tus herramientas.** Velas, cotizaciones, indicadores y estrategias, en una sola petición o en tiempo real. Proyecto comunitario independiente y no oficial.
+[![Tests](https://github.com/Mathieu2301/TradingView-API/actions/workflows/tests.yml/badge.svg?branch=main)](https://github.com/Mathieu2301/TradingView-API/actions/workflows/tests.yml) [![npm](https://badgen.net/npm/v/@mathieuc/tradingview)](https://www.npmjs.com/package/@mathieuc/tradingview) [![Stars](https://img.shields.io/github/stars/Mathieu2301/TradingView-API?style=social)](https://github.com/Mathieu2301/TradingView-API)
+
+<a href="https://trendshift.io/repositories/26416?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-26416" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/26416" alt="Mathieu2301/TradingView-API | #1 Repo Of The Day on Trendshift" width="250" height="55"/></a>
+
+![Demostración grabada: una consulta devuelve 40 velas diarias de BTC/USDT, representadas como un gráfico de líneas](../assets/readme-demo.gif)
+
+*Una consulta real de velas, grabada el 2 de octubre de 2026 con la versión preliminar de desarrollo (`fetchCandles`, llamada `getCandles` en la versión 4) y representada para esta demostración. Los precios no son en directo.*
+
+### Una consulta, datos reales
+
+> **La versión candidata V4 está disponible en npm bajo la etiqueta `next`.** Instálala con `npm install @mathieuc/tradingview@next`. La etiqueta predeterminada `latest` sigue en V3 y no exporta `getCandles`.
+
+```js
+import { getCandles } from '@mathieuc/tradingview/data';
+
+const candles = await getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: 'D', count: 40 });
+console.log(candles.at(-1)); // { time, open, high, low, close, volume }
+```
-> **¿Tienes un problema, una pregunta o una idea? [Abre un issue](https://github.com/Mathieu2301/TradingView-API/issues/new/choose).** No necesitas una reproducción perfecta para preguntar.
+¿Prefieres empezar sin código? También puedes usar las opciones de abajo.
-> **La versión 4 es una reescritura completa en TypeScript**, con una nueva API y sin capa de compatibilidad. ¿Vienes de la v3? Lee la [guía de migración](migration-v4.md) (en inglés). Todas las funciones de la v3 siguen disponibles: consulta la [matriz de cobertura](v4-coverage.md). Las versiones npm 3.x mantienen la API `Client` anterior.
+> **La versión 4 es una reescritura incompatible en TypeScript**, con una API nueva y sin capa de compatibilidad. ¿Vienes de V3? Lee la [guía de migración](migration-v4.md). Todas las funciones de V3 siguen disponibles: consulta la [matriz de cobertura](v4-coverage.md) y las [pruebas de fiabilidad](v4-reliability.md). El [informe de preparación de la RC](v4-stabilization.md) documenta las comprobaciones y los requisitos pendientes para la versión estable. Las versiones npm 3.x conservan la API `Client` anterior; comprueba la versión que instalas en la [página de npm](https://www.npmjs.com/package/@mathieuc/tradingview). Estas guías técnicas están en inglés.
-## Elige cómo empezar
+## Primeros pasos
-- **Instalación de V4 beta:** clona este repositorio y ejecuta `npm ci && npm run build && node examples/candles.js` (Node.js 20+ o Bun). **npm todavía entrega V3**, no las importaciones V4 de abajo. Consulta los [ejemplos](../examples).
-- **Con Claude Code, Codex, OpenClaw u otro asistente:** comparte este repositorio y la [guía de la API de datos](data-api.md).
-- **Sin instalación local:** [Molted](https://molted.cloud/) ofrece un espacio de trabajo con agente alojado que puede trabajar desde este repositorio. Es opcional.
+### Inicio rápido interactivo
+
+<!-- The launcher is introduced after 4.0.0-rc.0; keep this explicit until published. -->
+La próxima versión del paquete añadirá este asistente interactivo (no incluido en RC.0):
+
+```bash
+npx @mathieuc/tradingview@next
+```
+
+Ejecútalo desde el directorio de tu proyecto con Node.js 20+. Elige una opción:
+
+1. **Agente autónomo (recomendado)** — abre el [monitor de mercado TradingView-API en Molted Studio](https://molted.studio/dreams/market-watch-alerts). Sin configurar un proyecto local.
+2. **Claude Code CLI** — inicia tu CLI `claude` instalado en este directorio con un prompt de proyecto listo para usar.
+3. **Codex CLI** — inicia tu CLI `codex` instalado en este directorio con el mismo prompt.
+4. **Otro agente de programación local** — muestra el prompt para pegarlo en tu agente.
+5. **Instalar solo la biblioteca** — ejecuta `npm install @mathieuc/tradingview@next` aquí, sin generar archivos ni iniciar un agente.
+
+Claude Code y Codex deben estar instalados y autenticados. Sus solicitudes de permiso habituales siguen activadas. Si el inicio falla, se muestra el prompt para usarlo manualmente. Si no hay navegador disponible, el enlace alojado sigue visible.
+
+Usa `--choice 4` para mostrar el prompt directamente, o `--help` para consultar la ayuda. Las llamadas no interactivas deben pasar `--choice`. Para probar el asistente desde este repositorio antes de su publicación:
+
+```bash
+npm ci && npm run build
+node bin/tradingview.mjs
+```
+
+### Instalación manual
+
+```bash
+npm install @mathieuc/tradingview@next
+# O: bun add @mathieuc/tradingview@next
+```
+
+`next` instala la versión candidata V4; la etiqueta predeterminada `latest` todavía instala V3. No mezcles imports de V4 con una instalación de V3.
+
+El paquete V4 es ESM con declaraciones TypeScript. Los proyectos CommonJS pueden usar `require()` en Node 20.19+ o 22.12+, o `await import()`.
+
+### ¿Quieres contribuir?
+
+[Abre una issue](https://github.com/Mathieu2301/TradingView-API/issues/new/choose) para comentar una función o informar de un error, o envía una pull request. Las preguntas y las ideas son bienvenidas; no necesitas una reproducción perfecta para iniciar la conversación. `npm run check` ejecuta la comprobación de tipos, el lint, las pruebas, la compilación y la prueba del paquete.
## API de datos
-```ts
-import { getCandles, watchCandles, getQuote } from '@mathieuc/tradingview/data';
+La API de datos gestiona las conexiones, las sesiones, los tiempos de espera y la limpieza. Sirve para scripts, servidores, paneles, bots y agentes.
-const candles = await getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: 'D', count: 100 });
-console.log(candles.at(-1)); // { time, open, high, low, close, volume }, de la más antigua a la más reciente
+```ts
+import {
+ getCandles, watchCandles, getQuote, getIndicatorData, searchMarkets,
+} from '@mathieuc/tradingview/data';
+// One-shot: resolves with complete data, then releases everything.
+const hourly = await getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '60', count: 500 });
+const lastWeek = await getCandles({ symbol: 'NASDAQ:AAPL', timeframe: '15', from: new Date(Date.now() - 7 * 86_400_000) });
const quote = await getQuote('BINANCE:BTCUSDT');
+const [market] = await searchMarkets('ethereum', { type: 'crypto' });
+// Watcher: keeps streaming until stopped.
const watcher = await watchCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '1' }, {
- onData: (snapshot) => console.log(snapshot.at(-1)?.close),
- onError: console.error,
+ onData: (candles) => console.log(candles.at(-1)?.close),
+ onError: (error) => console.error(error.code, error.message),
});
await watcher.stop();
+
+// Indicators and strategies (Pine scripts need an account).
+const { values } = await getIndicatorData({
+ symbol: 'BINANCE:BTCUSDT', indicator: 'STD;RSI', credentials: { session, signature },
+});
```
-Cada función gestiona la conexión, el tiempo máximo (`timeoutMs`), la cancelación (`signal`) y la limpieza. Otras funciones: `getQuotes`, `watchQuotes`, `getSymbolInfo`, `getIndicatorData`, `watchIndicator`, `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis`, `getScreener`, `getHotlist`, `getWatchlists`. Detalles: [guía de la API de datos](data-api.md).
+| Necesidad | Función |
+| --- | --- |
+| Velas: barras recientes, historial profundo, rangos de fechas, Heikin Ashi/Renko/... | `getCandles`, `watchCandles` |
+| Cotizaciones: último precio, variación, bid/ask, volumen... | `getQuote`, `getQuotes`, `watchQuotes` |
+| Valores de indicadores, dibujos e informes de estrategias | `getIndicatorData`, `watchIndicator` |
+| Metadatos de símbolos | `getSymbolInfo` |
+| Screener de acciones/cripto y clasificaciones | `getScreener`, `getHotlist` |
+| Listas de seguimiento de la cuenta (solo lectura) | `getWatchlists` |
+| Búsqueda y evaluaciones | `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis` |
+
+Las funciones de datos WebSocket aceptan `timeoutMs`, un `AbortSignal`, credenciales de cuenta (`credentials`) y un `client` compartido opcional. Las consultas HTTP aceptan un `AbortSignal` en sus opciones. Los errores son `TradingViewError` con un `code` como `SYMBOL_ERROR`, `TIMEOUT` o `STUDY_ERROR`. Consulta todas las opciones en la [guía de la API de datos](data-api.md).
## API de bajo nivel
+Para un control completo (varios gráficos y estudios en una conexión, modo replay, paquetes sin procesar), usa directamente el cliente y las sesiones:
+
```ts
-import { TradingViewClient } from '@mathieuc/tradingview';
+import { TradingViewClient, getIndicator } from '@mathieuc/tradingview';
-const client = new TradingViewClient();
+const client = new TradingViewClient({ credentials: { session, signature } }); // Credentials are optional
const chart = client.createChart();
+
chart.on('update', () => console.log(chart.lastCandle?.close));
-chart.setMarket('BINANCE:BTCUSDT', { timeframe: 'D' });
-// Al terminar: await client.close();
+chart.on('error', (error) => console.error(error.message));
+chart.setMarket('BINANCE:BTCUSDT', { timeframe: '60', count: 300 });
+
+const supertrend = chart.createStudy(await getIndicator('STD;Supertrend'));
+supertrend.on('update', () => console.log(supertrend.values.at(-1)));
+
+// When your application is finished:
+await client.close();
```
-Gráficos, modo replay, estudios Pine e integrados, cotizaciones, cuentas, dibujos y permisos Pine: consulta la [referencia de bajo nivel](low-level-api.md) y los [ejemplos](../examples).
+La [referencia de la API de bajo nivel](low-level-api.md) cubre gráficos, replay, estudios, cotizaciones, funciones de cuenta y diseños, permisos Pine, transportes personalizados y utilidades del protocolo. Los [ejemplos](../examples) muestran cada función.
+
+## Cuentas y límites
+
+Sin una cuenta, TradingView ofrece datos limitados: menos historial intradía, sin estudios Pine y posibles fuentes retrasadas o alternativas. Con tus cookies `sessionid` y `sessionid_sign` (`credentials`), obtienes lo que tu cuenta permite. Guárdalas en variables de entorno o en un almacén de secretos; nunca en archivos fuente, issues o prompts.
-Sin cuenta, TradingView limita los datos (menos historial intradía, sin indicadores Pine). Con tus cookies `sessionid` y `sessionid_sign` (`credentials`), accedes a lo que permite tu cuenta. Guárdalas en variables de entorno, nunca en el código, issues o prompts.
+## Enlaces del proyecto
-[Repositorio GitHub](https://github.com/Mathieu2301/TradingView-API) · [Paquete npm](https://www.npmjs.com/package/@mathieuc/tradingview) · [Issues](https://github.com/Mathieu2301/TradingView-API/issues/new/choose)
+- [Repositorio GitHub](https://github.com/Mathieu2301/TradingView-API)
+- [Reconocimiento de la comunidad en Trendshift](https://trendshift.io/repositories/26416)
+- [Paquete npm](https://www.npmjs.com/package/@mathieuc/tradingview)
+- [Ejemplos](../examples)
+- [Informar de un error o solicitar una función](https://github.com/Mathieu2301/TradingView-API/issues/new/choose)
-TradingView es una marca de su propietario. Este proyecto no está afiliado ni respaldado por TradingView. Revisa los términos y permisos de datos de tu proveedor.
+TradingView es una marca de su respectivo propietario. Este proyecto no está afiliado a TradingView ni cuenta con su respaldo. Consulta las condiciones de tu proveedor y los permisos de datos de mercado aplicables a tu caso de uso.
diff --git a/docs/README.fr.md b/docs/README.fr.md
index 6915e45..307ac51 100644
--- a/docs/README.fr.md
+++ b/docs/README.fr.md
@@ -1,58 +1,150 @@
# TradingView-API
-**Essayez avec un agent hébergé :** [Créez votre veille de marché sur Molted Studio](https://molted.studio/fr/dreams/market-watch-alerts) — sans installation locale.
+**Construisez avec les données de marché, de votre premier graphique à une veille automatisée.** Récupérez des bougies et des cotations, exécutez des indicateurs et des stratégies, et transformez vos idées en outils. Projet communautaire indépendant, pas une API officielle de TradingView.
-<a href="https://trendshift.io/repositories/26416?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-26416" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/26416" alt="Mathieu2301/TradingView-API | #1 Repo Of The Day on Trendshift" width="250" height="55"/></a>
+[Démarrer](#démarrer) · [Explorer les exemples](../examples) · [Lire le guide de l’API de données](data-api.md)
**Langue :** [English](../README.md) · Français · [Español](README.es.md) · [Português](README.pt.md)
-**Des données de marché et des indicateurs pour construire vos outils.** Bougies, cotations, indicateurs et stratégies, en une requête ou en temps réel. Projet communautaire indépendant, non officiel.
+[![Tests](https://github.com/Mathieu2301/TradingView-API/actions/workflows/tests.yml/badge.svg?branch=main)](https://github.com/Mathieu2301/TradingView-API/actions/workflows/tests.yml) [![npm](https://badgen.net/npm/v/@mathieuc/tradingview)](https://www.npmjs.com/package/@mathieuc/tradingview) [![Stars](https://img.shields.io/github/stars/Mathieu2301/TradingView-API?style=social)](https://github.com/Mathieu2301/TradingView-API)
+
+<a href="https://trendshift.io/repositories/26416?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-26416" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/26416" alt="Mathieu2301/TradingView-API | #1 Repo Of The Day on Trendshift" width="250" height="55"/></a>
+
+![Démonstration enregistrée : une requête renvoie 40 bougies quotidiennes BTC/USDT, représentées en courbe](../assets/readme-demo.gif)
+
+*Une vraie requête de bougies, enregistrée le 2 octobre 2026 avec la préversion de développement (`fetchCandles`, appelée `getCandles` en version 4), puis représentée pour cette démonstration. Les prix ne sont pas en direct.*
+
+### Une requête, de vraies données
+
+> **La release candidate V4 est disponible sur npm sous le tag `next`.** Installez-la avec `npm install @mathieuc/tradingview@next`. Le tag par défaut `latest` reste sur la V3 et n’exporte pas `getCandles`.
+
+```js
+import { getCandles } from '@mathieuc/tradingview/data';
+
+const candles = await getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: 'D', count: 40 });
+console.log(candles.at(-1)); // { time, open, high, low, close, volume }
+```
-> **Un problème, une question ou une idée ? [Ouvrez une issue](https://github.com/Mathieu2301/TradingView-API/issues/new/choose).** Pas besoin d'avoir déjà une reproduction parfaite.
+Vous préférez commencer sans coder ? Les parcours ci-dessous le permettent aussi.
-> **La version 4 est une réécriture complète en TypeScript**, avec une nouvelle API et sans couche de compatibilité. Vous venez de la v3 ? Lisez le [guide de migration](migration-v4.md) (en anglais). Toutes les fonctionnalités de la v3 restent disponibles : voir la [matrice de couverture](v4-coverage.md). Les versions npm 3.x gardent l'ancienne API `Client`.
+> **La version 4 est une réécriture incompatible en TypeScript**, avec une nouvelle API et sans couche de compatibilité. Vous venez de la V3 ? Lisez le [guide de migration](migration-v4.md). Toutes les fonctionnalités V3 restent disponibles : voir la [matrice de couverture](v4-coverage.md) et les [preuves de fiabilité](v4-reliability.md). Le [rapport de préparation de la RC](v4-stabilization.md) suit les vérifications et les conditions restantes avant publication stable. Les versions npm 3.x conservent l’ancienne API `Client` ; vérifiez la version installée sur la [page npm](https://www.npmjs.com/package/@mathieuc/tradingview). Ces guides techniques sont en anglais.
-## Choisissez votre parcours
+## Démarrer
-- **Installation de la V4 bêta :** clonez ce dépôt, puis lancez `npm ci && npm run build && node examples/candles.js` (Node.js 20+ ou Bun). **npm fournit encore la V3**, pas les imports V4 ci-dessous. Consultez les [exemples](../examples).
-- **Avec Claude Code, Codex, OpenClaw ou un autre assistant :** donnez-lui ce dépôt et le [guide de l'API de données](data-api.md).
-- **Sans installation locale :** [Molted](https://molted.cloud/) propose un espace d'agent hébergé pouvant travailler à partir de ce dépôt. Ce choix est facultatif.
+### Quick-start interactif
+
+<!-- The launcher is introduced after 4.0.0-rc.0; keep this explicit until published. -->
+La prochaine version du paquet ajoutera ce lanceur interactif (absent de RC.0) :
+
+```bash
+npx @mathieuc/tradingview@next
+```
+
+Lancez-le depuis le dossier de votre projet avec Node.js 20+. Choisissez un parcours :
+
+1. **Agent autonome (recommandé)** — ouvre la [veille de marché TradingView-API sur Molted Studio](https://molted.studio/fr/dreams/market-watch-alerts). Aucune configuration de projet local.
+2. **Claude Code CLI** — démarre votre CLI `claude` installé dans ce dossier, avec un prompt de projet prêt à l’emploi.
+3. **Codex CLI** — démarre votre CLI `codex` installé dans ce dossier, avec le même prompt.
+4. **Un autre coding-agent local** — affiche le prompt à coller dans votre agent.
+5. **Installer seulement la librairie** — exécute `npm install @mathieuc/tradingview@next` dans ce dossier, sans générer de fichiers ni démarrer d’agent.
+
+Claude Code et Codex doivent déjà être installés et authentifiés. Leurs demandes d’autorisation habituelles restent actives. Si le lancement échoue, le prompt est affiché pour une utilisation manuelle. Si aucun navigateur n’est disponible, le lien hébergé reste visible.
+
+Utilisez `--choice 4` pour afficher directement le prompt, ou `--help` pour l’aide. En mode non interactif, `--choice` est obligatoire. Pour essayer le lanceur depuis ce dépôt avant publication :
+
+```bash
+npm ci && npm run build
+node bin/tradingview.mjs
+```
+
+### Installation manuelle
+
+```bash
+npm install @mathieuc/tradingview@next
+# Ou : bun add @mathieuc/tradingview@next
+```
+
+`next` installe la release candidate V4 ; le tag par défaut `latest` installe encore la V3. Ne mélangez pas les imports V4 avec une installation V3.
+
+Le paquet V4 est ESM avec des déclarations TypeScript. Les projets CommonJS peuvent utiliser `require()` avec Node 20.19+ ou 22.12+, ou `await import()`.
+
+### Envie de contribuer ?
+
+[Ouvrez une issue](https://github.com/Mathieu2301/TradingView-API/issues/new/choose) pour discuter d’une fonctionnalité ou signaler un bug, ou proposez une pull request. Questions et idées sont bienvenues ; une reproduction parfaite n’est pas nécessaire pour engager la discussion. `npm run check` lance la vérification des types, le lint, les tests, la compilation et le test du paquet.
## API de données
-```ts
-import { getCandles, watchCandles, getQuote } from '@mathieuc/tradingview/data';
+L’API de données gère les connexions, les sessions, les délais et le nettoyage à votre place. Elle convient aux scripts, serveurs, tableaux de bord, bots et agents.
-const candles = await getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: 'D', count: 100 });
-console.log(candles.at(-1)); // { time, open, high, low, close, volume }, du plus ancien au plus récent
+```ts
+import {
+ getCandles, watchCandles, getQuote, getIndicatorData, searchMarkets,
+} from '@mathieuc/tradingview/data';
+// One-shot: resolves with complete data, then releases everything.
+const hourly = await getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '60', count: 500 });
+const lastWeek = await getCandles({ symbol: 'NASDAQ:AAPL', timeframe: '15', from: new Date(Date.now() - 7 * 86_400_000) });
const quote = await getQuote('BINANCE:BTCUSDT');
+const [market] = await searchMarkets('ethereum', { type: 'crypto' });
+// Watcher: keeps streaming until stopped.
const watcher = await watchCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '1' }, {
- onData: (snapshot) => console.log(snapshot.at(-1)?.close),
- onError: console.error,
+ onData: (candles) => console.log(candles.at(-1)?.close),
+ onError: (error) => console.error(error.code, error.message),
});
await watcher.stop();
+
+// Indicators and strategies (Pine scripts need an account).
+const { values } = await getIndicatorData({
+ symbol: 'BINANCE:BTCUSDT', indicator: 'STD;RSI', credentials: { session, signature },
+});
```
-Chaque fonction gère la connexion, le délai maximal (`timeoutMs`), l'annulation (`signal`) et le nettoyage. Autres fonctions : `getQuotes`, `watchQuotes`, `getSymbolInfo`, `getIndicatorData`, `watchIndicator`, `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis`, `getScreener`, `getHotlist`, `getWatchlists`. Détails : [guide de l'API de données](data-api.md).
+| Besoin | Fonction |
+| --- | --- |
+| Bougies : dernières barres, historique profond, plages de dates, Heikin Ashi/Renko/... | `getCandles`, `watchCandles` |
+| Cotations : dernier prix, variation, bid/ask, volume... | `getQuote`, `getQuotes`, `watchQuotes` |
+| Valeurs d’indicateurs, dessins et rapports de stratégie | `getIndicatorData`, `watchIndicator` |
+| Métadonnées des symboles | `getSymbolInfo` |
+| Screener actions/crypto et classements | `getScreener`, `getHotlist` |
+| Listes de suivi du compte (lecture seule) | `getWatchlists` |
+| Recherche et évaluations | `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis` |
+
+Les fonctions de données WebSocket acceptent `timeoutMs`, un `AbortSignal`, les identifiants du compte (`credentials`) et un `client` partagé facultatif. Les requêtes HTTP acceptent un `AbortSignal` via leurs options. Les erreurs sont des `TradingViewError` avec un `code` comme `SYMBOL_ERROR`, `TIMEOUT` ou `STUDY_ERROR`. Le [guide de l’API de données](data-api.md) détaille toutes les options.
## API bas niveau
+Pour un contrôle complet (plusieurs graphiques et études sur une connexion, mode replay, paquets bruts), utilisez directement le client et les sessions :
+
```ts
-import { TradingViewClient } from '@mathieuc/tradingview';
+import { TradingViewClient, getIndicator } from '@mathieuc/tradingview';
-const client = new TradingViewClient();
+const client = new TradingViewClient({ credentials: { session, signature } }); // Credentials are optional
const chart = client.createChart();
+
chart.on('update', () => console.log(chart.lastCandle?.close));
-chart.setMarket('BINANCE:BTCUSDT', { timeframe: 'D' });
-// À la fin : await client.close();
+chart.on('error', (error) => console.error(error.message));
+chart.setMarket('BINANCE:BTCUSDT', { timeframe: '60', count: 300 });
+
+const supertrend = chart.createStudy(await getIndicator('STD;Supertrend'));
+supertrend.on('update', () => console.log(supertrend.values.at(-1)));
+
+// When your application is finished:
+await client.close();
```
-Graphiques, mode replay, études Pine et intégrées, cotations, comptes, dessins et permissions Pine : voir la [référence bas niveau](low-level-api.md) et les [exemples](../examples).
+La [référence de l’API bas niveau](low-level-api.md) couvre les graphiques, le replay, les études, les cotations, les comptes et les mises en page, les permissions Pine, les transports personnalisés et les outils du protocole. Les [exemples](../examples) illustrent chaque fonctionnalité.
+
+## Comptes et limites
+
+Sans compte, TradingView fournit des données limitées : historique intraday réduit, pas d’études Pine et flux éventuellement différés ou de substitution. Avec vos cookies `sessionid` et `sessionid_sign` (`credentials`), vous accédez à ce que permet votre compte. Gardez-les dans des variables d’environnement ou un gestionnaire de secrets ; jamais dans les fichiers source, les issues ou les prompts.
-Sans compte, TradingView limite les données (historique intraday réduit, pas d'indicateurs Pine). Avec vos cookies `sessionid` et `sessionid_sign` (`credentials`), vous accédez à ce que permet votre compte. Gardez-les dans des variables d'environnement, jamais dans le code, les issues ou les prompts.
+## Liens du projet
-[Dépôt GitHub](https://github.com/Mathieu2301/TradingView-API) · [Package npm](https://www.npmjs.com/package/@mathieuc/tradingview) · [Issues](https://github.com/Mathieu2301/TradingView-API/issues/new/choose)
+- [Dépôt GitHub](https://github.com/Mathieu2301/TradingView-API)
+- [Mise en avant communautaire sur Trendshift](https://trendshift.io/repositories/26416)
+- [Paquet npm](https://www.npmjs.com/package/@mathieuc/tradingview)
+- [Exemples](../examples)
+- [Signaler un bug ou proposer une fonctionnalité](https://github.com/Mathieu2301/TradingView-API/issues/new/choose)
-TradingView est une marque de son propriétaire. Ce projet n'est ni affilié ni approuvé par TradingView. Vérifiez les conditions d'utilisation et droits sur les données de votre fournisseur.
+TradingView est une marque de son propriétaire. Ce projet n’est ni affilié à TradingView ni approuvé par TradingView. Vérifiez les conditions de votre fournisseur de données et les autorisations applicables à votre usage.
diff --git a/docs/README.pt.md b/docs/README.pt.md
index edce0cb..5f02d52 100644
--- a/docs/README.pt.md
+++ b/docs/README.pt.md
@@ -1,58 +1,150 @@
# TradingView-API
-**Experimente com um agente hospedado:** [Crie um monitor de mercado no Molted Studio](https://molted.studio/dreams/market-watch-alerts) — sem instalação local.
+**Crie com dados de mercado, do primeiro gráfico a um monitor em funcionamento.** Obtenha candles e cotações, execute indicadores e estratégias e transforme ideias em ferramentas. Um projeto comunitário independente, não uma API oficial do TradingView.
-<a href="https://trendshift.io/repositories/26416?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-26416" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/26416" alt="Mathieu2301/TradingView-API | #1 Repo Of The Day on Trendshift" width="250" height="55"/></a>
+[Primeiros passos](#primeiros-passos) · [Explorar exemplos](../examples) · [Ler o guia da API de dados](data-api.md)
**Idioma:** [English](../README.md) · [Français](README.fr.md) · [Español](README.es.md) · Português
-**Dados de mercado e indicadores para construir suas ferramentas.** Candles, cotações, indicadores e estratégias, em uma única requisição ou em tempo real. Projeto comunitário independente e não oficial.
+[![Tests](https://github.com/Mathieu2301/TradingView-API/actions/workflows/tests.yml/badge.svg?branch=main)](https://github.com/Mathieu2301/TradingView-API/actions/workflows/tests.yml) [![npm](https://badgen.net/npm/v/@mathieuc/tradingview)](https://www.npmjs.com/package/@mathieuc/tradingview) [![Stars](https://img.shields.io/github/stars/Mathieu2301/TradingView-API?style=social)](https://github.com/Mathieu2301/TradingView-API)
+
+<a href="https://trendshift.io/repositories/26416?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-26416" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/26416" alt="Mathieu2301/TradingView-API | #1 Repo Of The Day on Trendshift" width="250" height="55"/></a>
+
+![Demonstração gravada: uma consulta retorna 40 candles diários de BTC/USDT, exibidos em um gráfico de linhas](../assets/readme-demo.gif)
+
+*Uma consulta real de candles, gravada em 2 de outubro de 2026 com a prévia de desenvolvimento (`fetchCandles`, chamada `getCandles` na versão 4) e representada para esta demonstração. Os preços não estão em tempo real.*
+
+### Uma consulta, dados reais
+
+> **A release candidate V4 está disponível no npm com a tag `next`.** Instale com `npm install @mathieuc/tradingview@next`. A tag padrão `latest` continua na V3 e não exporta `getCandles`.
+
+```js
+import { getCandles } from '@mathieuc/tradingview/data';
+
+const candles = await getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: 'D', count: 40 });
+console.log(candles.at(-1)); // { time, open, high, low, close, volume }
+```
-> **Tem um problema, uma dúvida ou uma ideia? [Abra uma issue](https://github.com/Mathieu2301/TradingView-API/issues/new/choose).** Não é preciso ter uma reprodução perfeita para perguntar.
+Prefere começar sem código? Os caminhos abaixo também funcionam.
-> **A versão 4 é uma reescrita completa em TypeScript**, com uma nova API e sem camada de compatibilidade. Vindo da v3? Leia o [guia de migração](migration-v4.md) (em inglês). Todos os recursos da v3 continuam disponíveis: veja a [matriz de cobertura](v4-coverage.md). As versões npm 3.x mantêm a API `Client` anterior.
+> **A versão 4 é uma reescrita incompatível em TypeScript**, com uma nova API e sem camada de compatibilidade. Vem da V3? Leia o [guia de migração](migration-v4.md). Todas as funcionalidades da V3 continuam disponíveis: veja a [matriz de cobertura](v4-coverage.md) e as [evidências de confiabilidade](v4-reliability.md). O [relatório de preparação da RC](v4-stabilization.md) acompanha as verificações e os requisitos pendentes para a versão estável. As versões npm 3.x mantêm a API `Client` anterior; confira a versão instalada na [página do npm](https://www.npmjs.com/package/@mathieuc/tradingview). Esses guias técnicos estão em inglês.
-## Escolha como começar
+## Primeiros passos
-- **Instalação da V4 beta:** clone este repositório e execute `npm ci && npm run build && node examples/candles.js` (Node.js 20+ ou Bun). **O npm ainda entrega a V3**, não os imports V4 abaixo. Consulte os [exemplos](../examples).
-- **Com Claude Code, Codex, OpenClaw ou outro assistente:** compartilhe este repositório e o [guia da API de dados](data-api.md).
-- **Sem instalação local:** o [Molted](https://molted.cloud/) oferece um espaço de agente hospedado que pode trabalhar a partir deste repositório. É opcional.
+### Início rápido interativo
+
+<!-- The launcher is introduced after 4.0.0-rc.0; keep this explicit until published. -->
+A próxima versão do pacote incluirá este assistente interativo (não incluído na RC.0):
+
+```bash
+npx @mathieuc/tradingview@next
+```
+
+Execute no diretório do seu projeto com Node.js 20+. Escolha um caminho:
+
+1. **Agente autônomo (recomendado)** — abre o [monitor de mercado TradingView-API no Molted Studio](https://molted.studio/dreams/market-watch-alerts). Sem configurar um projeto local.
+2. **Claude Code CLI** — inicia seu CLI `claude` instalado neste diretório com um prompt de projeto pronto para usar.
+3. **Codex CLI** — inicia seu CLI `codex` instalado neste diretório com o mesmo prompt.
+4. **Outro agente de programação local** — exibe o prompt para colar no seu agente.
+5. **Instalar apenas a biblioteca** — executa `npm install @mathieuc/tradingview@next` aqui, sem gerar arquivos nem iniciar um agente.
+
+Claude Code e Codex devem estar instalados e autenticados. As solicitações normais de permissão continuam ativas. Se a inicialização falhar, o prompt será exibido para uso manual. Se não houver navegador disponível, o link hospedado continuará visível.
+
+Use `--choice 4` para exibir o prompt diretamente ou `--help` para consultar a ajuda. Chamadas não interativas devem passar `--choice`. Para testar o assistente a partir deste repositório antes da publicação:
+
+```bash
+npm ci && npm run build
+node bin/tradingview.mjs
+```
+
+### Instalação manual
+
+```bash
+npm install @mathieuc/tradingview@next
+# Ou: bun add @mathieuc/tradingview@next
+```
+
+`next` instala a release candidate V4; a tag padrão `latest` ainda instala a V3. Não misture imports da V4 com uma instalação da V3.
+
+O pacote V4 é ESM com declarações TypeScript. Projetos CommonJS podem usar `require()` no Node 20.19+ ou 22.12+, ou `await import()`.
+
+### Quer contribuir?
+
+[Abra uma issue](https://github.com/Mathieu2301/TradingView-API/issues/new/choose) para discutir uma funcionalidade ou relatar um bug, ou envie uma pull request. Perguntas e ideias são bem-vindas; não é preciso ter uma reprodução perfeita para iniciar uma conversa. `npm run check` executa a verificação de tipos, o lint, os testes, a compilação e o teste do pacote.
## API de dados
-```ts
-import { getCandles, watchCandles, getQuote } from '@mathieuc/tradingview/data';
+A API de dados gerencia conexões, sessões, tempos limite e limpeza para você. É adequada para scripts, servidores, painéis, bots e agentes.
-const candles = await getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: 'D', count: 100 });
-console.log(candles.at(-1)); // { time, open, high, low, close, volume }, do mais antigo ao mais recente
+```ts
+import {
+ getCandles, watchCandles, getQuote, getIndicatorData, searchMarkets,
+} from '@mathieuc/tradingview/data';
+// One-shot: resolves with complete data, then releases everything.
+const hourly = await getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '60', count: 500 });
+const lastWeek = await getCandles({ symbol: 'NASDAQ:AAPL', timeframe: '15', from: new Date(Date.now() - 7 * 86_400_000) });
const quote = await getQuote('BINANCE:BTCUSDT');
+const [market] = await searchMarkets('ethereum', { type: 'crypto' });
+// Watcher: keeps streaming until stopped.
const watcher = await watchCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '1' }, {
- onData: (snapshot) => console.log(snapshot.at(-1)?.close),
- onError: console.error,
+ onData: (candles) => console.log(candles.at(-1)?.close),
+ onError: (error) => console.error(error.code, error.message),
});
await watcher.stop();
+
+// Indicators and strategies (Pine scripts need an account).
+const { values } = await getIndicatorData({
+ symbol: 'BINANCE:BTCUSDT', indicator: 'STD;RSI', credentials: { session, signature },
+});
```
-Cada função cuida da conexão, do tempo máximo (`timeoutMs`), do cancelamento (`signal`) e da limpeza. Outras funções: `getQuotes`, `watchQuotes`, `getSymbolInfo`, `getIndicatorData`, `watchIndicator`, `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis`, `getScreener`, `getHotlist`, `getWatchlists`. Detalhes: [guia da API de dados](data-api.md).
+| Necessidade | Função |
+| --- | --- |
+| Candles: barras recentes, histórico profundo, intervalos de datas, Heikin Ashi/Renko/... | `getCandles`, `watchCandles` |
+| Cotações: último preço, variação, bid/ask, volume... | `getQuote`, `getQuotes`, `watchQuotes` |
+| Valores de indicadores, desenhos e relatórios de estratégias | `getIndicatorData`, `watchIndicator` |
+| Metadados de símbolos | `getSymbolInfo` |
+| Screener de ações/cripto e rankings | `getScreener`, `getHotlist` |
+| Listas de acompanhamento da conta (somente leitura) | `getWatchlists` |
+| Pesquisa e avaliações | `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis` |
+
+As funções de dados WebSocket aceitam `timeoutMs`, um `AbortSignal`, credenciais da conta (`credentials`) e um `client` compartilhado opcional. Consultas HTTP aceitam um `AbortSignal` nas opções. Os erros são `TradingViewError` com um `code` como `SYMBOL_ERROR`, `TIMEOUT` ou `STUDY_ERROR`. Veja todas as opções no [guia da API de dados](data-api.md).
## API de baixo nível
+Para controle completo (vários gráficos e estudos em uma conexão, modo replay, pacotes brutos), use o cliente e as sessões diretamente:
+
```ts
-import { TradingViewClient } from '@mathieuc/tradingview';
+import { TradingViewClient, getIndicator } from '@mathieuc/tradingview';
-const client = new TradingViewClient();
+const client = new TradingViewClient({ credentials: { session, signature } }); // Credentials are optional
const chart = client.createChart();
+
chart.on('update', () => console.log(chart.lastCandle?.close));
-chart.setMarket('BINANCE:BTCUSDT', { timeframe: 'D' });
-// Ao terminar: await client.close();
+chart.on('error', (error) => console.error(error.message));
+chart.setMarket('BINANCE:BTCUSDT', { timeframe: '60', count: 300 });
+
+const supertrend = chart.createStudy(await getIndicator('STD;Supertrend'));
+supertrend.on('update', () => console.log(supertrend.values.at(-1)));
+
+// When your application is finished:
+await client.close();
```
-Gráficos, modo replay, estudos Pine e integrados, cotações, contas, desenhos e permissões Pine: veja a [referência de baixo nível](low-level-api.md) e os [exemplos](../examples).
+A [referência da API de baixo nível](low-level-api.md) cobre gráficos, replay, estudos, cotações, funções de conta e layouts, permissões Pine, transportes personalizados e utilitários do protocolo. Os [exemplos](../examples) mostram cada funcionalidade.
+
+## Contas e limites
+
+Sem uma conta, o TradingView fornece dados limitados: histórico intradiário reduzido, sem estudos Pine e possíveis fontes atrasadas ou alternativas. Com seus cookies `sessionid` e `sessionid_sign` (`credentials`), você obtém o que sua conta permite. Guarde-os em variáveis de ambiente ou em um gerenciador de segredos; nunca em arquivos-fonte, issues ou prompts.
-Sem conta, o TradingView limita os dados (menos histórico intraday, sem indicadores Pine). Com seus cookies `sessionid` e `sessionid_sign` (`credentials`), você acessa o que sua conta permite. Guarde-os em variáveis de ambiente, nunca no código, em issues ou prompts.
+## Links do projeto
-[Repositório GitHub](https://github.com/Mathieu2301/TradingView-API) · [Pacote npm](https://www.npmjs.com/package/@mathieuc/tradingview) · [Issues](https://github.com/Mathieu2301/TradingView-API/issues/new/choose)
+- [Repositório GitHub](https://github.com/Mathieu2301/TradingView-API)
+- [Destaque da comunidade no Trendshift](https://trendshift.io/repositories/26416)
+- [Pacote npm](https://www.npmjs.com/package/@mathieuc/tradingview)
+- [Exemplos](../examples)
+- [Relatar um bug ou solicitar uma funcionalidade](https://github.com/Mathieu2301/TradingView-API/issues/new/choose)
-TradingView é uma marca do seu proprietário. Este projeto não é afiliado nem endossado pelo TradingView. Verifique os termos e permissões de dados do seu provedor.
+TradingView é uma marca de seu respectivo proprietário. Este projeto não é afiliado ao TradingView nem endossado por ele. Confira os termos do seu provedor de dados e as permissões de dados de mercado aplicáveis ao seu caso de uso.
diff --git a/llms.txt b/llms.txt
index ccc4cfb..8c5aa3b 100644
--- a/llms.txt
+++ b/llms.txt
@@ -3,7 +3,7 @@
# https://www.npmjs.com/package/@mathieuc/tradingview
Independent community library for TradingView market data. Not an official TradingView API.
-Version 4 beta: TypeScript, ESM, Node >= 20 or Bun. Breaking rewrite of v3 (no compatibility layer). Install the prerelease with npm install @mathieuc/tradingview@beta; the default latest tag remains v3.
+Version 4 release candidate: TypeScript, ESM, Node >= 20 or Bun. Breaking rewrite of v3 (no compatibility layer). Install the prerelease with npm install @mathieuc/tradingview@next; the default latest tag remains v3.
Simple data API (import from '@mathieuc/tradingview/data' or the root entry):
- getCandles({ symbol, timeframe?, count?, from?, to?, chartType?, ... }) -> Candle[] oldest first, time in Unix seconds.
@@ -22,5 +22,5 @@ Low-level API: TradingViewClient, client.createChart() (ChartSession: setMarket,
Pine studies need a TradingView account (session cookies). Built-in studies and candles/quotes work anonymously, with history limits.
Docs: docs/data-api.md, docs/low-level-api.md, docs/migration-v4.md, docs/v4-coverage.md, docs/v4-reliability.md, docs/protocol-contributing.md. Examples: examples/.
-No CLI, MCP server, backtesting engine or hosted trading API is shipped. Do not claim otherwise.
+The next release adds an interactive setup CLI: npx @mathieuc/tradingview@next (not present in RC.0). It opens Molted Studio, launches a local coding agent with a prompt, prints that prompt, or installs the library. It is not a market-data query CLI. No MCP server, backtesting engine or hosted trading API is shipped.
Questions and bugs: https://github.com/Mathieu2301/TradingView-API/issues/new/choose
diff --git a/package-lock.json b/package-lock.json
index a7c1f20..a270f51 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -23,6 +23,9 @@
},
"engines": {
"node": ">=20.0.0"
+ },
+ "bin": {
+ "tradingview": "bin/tradingview.mjs"
}
},
"node_modules/@babel/helper-string-parser": {
diff --git a/package.json b/package.json
index 93fc8ea..14ec439 100644
--- a/package.json
+++ b/package.json
@@ -27,7 +27,8 @@
"assets",
"llms.txt",
"examples",
- "scripts/parity.mjs"
+ "scripts/parity.mjs",
+ "bin"
],
"sideEffects": false,
"scripts": {
@@ -84,5 +85,8 @@
"homepage": "https://github.com/Mathieu2301/TradingView-API#readme",
"bugs": {
"url": "https://github.com/Mathieu2301/TradingView-API/issues"
+ },
+ "bin": {
+ "tradingview": "bin/tradingview.mjs"
}
}
diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs
index a16a039..c598f3e 100644
--- a/scripts/smoke.mjs
+++ b/scripts/smoke.mjs
@@ -3,7 +3,7 @@
// that both entry points load (ESM + type declarations) under Node and Bun.
// No TradingView call is made; installing the tarball may access the npm registry.
import { execFileSync, spawnSync } from 'node:child_process';
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
@@ -21,7 +21,7 @@ const dir = mkdtempSync(join(tmpdir(), 'tv-smoke-'));
try {
const packed = JSON.parse(run('npm', ['pack', '--json', '--pack-destination', dir], root))[0];
const files = packed.files.map((f) => f.path);
- for (const required of ['dist/index.js', 'dist/index.d.ts', 'dist/data/index.js', 'dist/data/index.d.ts', 'README.md', 'llms.txt', 'scripts/endurance.mjs', 'scripts/probe-account.mjs', 'scripts/parity.mjs', 'examples/screener.js']) {
+ for (const required of ['bin/tradingview.mjs', 'dist/quick-start.js', 'dist/index.js', 'dist/index.d.ts', 'dist/data/index.js', 'dist/data/index.d.ts', 'README.md', 'llms.txt', 'scripts/endurance.mjs', 'scripts/probe-account.mjs', 'scripts/parity.mjs', 'examples/screener.js']) {
if (!files.includes(required)) throw new Error(`Missing ${required} in package`);
}
if (files.some((f) => f.startsWith('src/') || f.startsWith('tests/'))) throw new Error('Sources or tests leaked into package');
@@ -30,6 +30,38 @@ try {
writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'smoke', private: true, type: 'module' }));
run('npm', ['install', '--no-audit', '--no-fund', '--ignore-scripts', join(dir, packed.filename)], dir);
+ const launcher = join(dir, 'node_modules', '@mathieuc', 'tradingview', 'bin', 'tradingview.mjs');
+ const help = run('node', [launcher, '--help'], dir);
+ if (!help.includes('Autonomous agent (recommended)')) throw new Error('CLI help missing');
+ const prompt = run('node', [launcher, '--choice', '4'], dir);
+ if (!prompt.includes('@mathieuc/tradingview@next')) throw new Error('CLI prompt missing');
+ const noTty = spawnSync('node', [launcher], { cwd: dir, encoding: 'utf8' });
+ if (noTty.status !== 1 || !noTty.stderr.includes('--choice')) throw new Error('CLI non-TTY guard failed');
+ const bin = join(dir, 'node_modules', '.bin', 'tradingview');
+ if (!run(bin, ['--help'], dir).includes('TradingView-API quick-start')) throw new Error('CLI bin link missing');
+ // Exercise real child-process argv and cwd without launching paid agents or
+ // installing another registry package. This job runs on Linux in CI.
+ const fakeBin = join(dir, 'fake bin');
+ mkdirSync(fakeBin);
+ const captured = join(dir, 'captured.json');
+ const { AGENT_PROMPT } = await import('../dist/quick-start.js');
+ for (const [choice, command] of [['2', 'claude'], ['3', 'codex'], ['5', 'npm']]) {
+ const executable = join(fakeBin, command);
+ writeFileSync(executable, `#!${process.execPath}
+import { writeFileSync } from 'node:fs';
+writeFileSync(process.env.TV_CAPTURE, JSON.stringify({ args: process.argv.slice(2), cwd: process.cwd() }));
+`);
+ chmodSync(executable, 0o755);
+ const child = spawnSync(process.execPath, [launcher, '--choice', choice], {
+ cwd: dir, encoding: 'utf8', env: { ...process.env, PATH: fakeBin + ':' + process.env.PATH, TV_CAPTURE: captured },
+ });
+ if (child.status !== 0) throw new Error(`CLI choice ${choice} failed: ${child.stderr}`);
+ const received = JSON.parse(readFileSync(captured, 'utf8'));
+ const expected = choice === '5' ? ['install', '@mathieuc/tradingview@next'] : [AGENT_PROMPT];
+ if (received.cwd !== dir || JSON.stringify(received.args) !== JSON.stringify(expected)) throw new Error(`CLI choice ${choice} altered argv or cwd`);
+ }
+ console.log('quick-start packed CLI ok');
+
const check = `
import * as tv from '@mathieuc/tradingview';
import { getCandles, watchQuotes, TradingViewError, TradingViewProvider } from '@mathieuc/tradingview/data';
diff --git a/src/quick-start.ts b/src/quick-start.ts
new file mode 100644
index 0000000..af7ebc1
--- /dev/null
+++ b/src/quick-start.ts
@@ -0,0 +1,125 @@
+import { spawnSync, type SpawnSyncOptions, type SpawnSyncReturns } from 'node:child_process';
+import { createInterface } from 'node:readline/promises';
+
+export const LANDING_URL = 'https://molted.studio/dreams/market-watch-alerts';
+export const PACKAGE_SPEC = '@mathieuc/tradingview@next';
+export const AGENT_PROMPT = `Help me build a project using TradingView-API V4 (${PACKAGE_SPEC}).
+First ask what I want to build and inspect the current project and its instructions before making changes.
+Read https://github.com/Mathieu2301/TradingView-API/blob/main/llms.txt and the data API guide at https://github.com/Mathieu2301/TradingView-API/blob/main/docs/data-api.md; use the docs shipped with the installed package as the version-specific reference.
+Use Node.js 20+ and install ${PACKAGE_SPEC} with the project's package manager. The default latest tag is still V3: do not mix the V3 Client API with V4.
+Preserve existing files and project configuration. For a new project, start with a small runnable ESM (.mjs) example using getCandles from '@mathieuc/tradingview/data' and anonymous BINANCE:BTCUSDT data, then adapt it to my goal.
+Use timeouts, handle errors, and stop watchers or close clients on shutdown. Run the example and report observed results honestly, with exact commands to run it again.
+Only request TradingView credentials if my feature needs them; keep them in local environment variables, out of source control and logs. Explain any account or market-data limitations relevant to my goal.
+This is an independent community library, not an official TradingView API. Do not assume it provides broker order execution.`;
+
+export const HELP = `TradingView-API quick-start (Node.js 20+)
+
+Usage: npx @mathieuc/tradingview@next [--choice 1|2|3|4|5]
+
+1. Autonomous agent (recommended)
+2. Claude Code CLI
+3. Codex CLI
+4. Another local coding agent
+5. Install the library only
+
+Run inside your project directory. Options 2 and 3 require an installed,
+authenticated CLI and keep its normal permission prompts. Option 5 runs
+npm install ${PACKAGE_SPEC} in the current directory.
+Use --choice for non-interactive selection; --help shows this message.
+`;
+
+type Runner = (command: string, args: string[], options: SpawnSyncOptions) => Pick<SpawnSyncReturns<Buffer>, 'status' | 'signal' | 'error'>;
+interface Runtime {
+ run?: Runner;
+ log?: (text: string) => void;
+ platform?: NodeJS.Platform;
+ env?: NodeJS.ProcessEnv;
+}
+
+function printPrompt(log: (text: string) => void): void {
+ log(`Paste this prompt into your coding agent:\n\n${AGENT_PROMPT}\n`);
+}
+
+function openLanding({ run, log, platform, env }: Required<Runtime>): number {
+ log(`Continue with an autonomous agent:\n${LANDING_URL}`);
+ const [command, args]: [string, string[]] = platform === 'darwin' ? ['open', [LANDING_URL]]
+ : platform === 'win32' ? ['rundll32.exe', ['url.dll,FileProtocolHandler', LANDING_URL]]
+ : ['xdg-open', [LANDING_URL]];
+ const result = run(command, args, { stdio: 'ignore', timeout: 10_000, env });
+ if (result.error || result.status !== 0) log('Could not open a browser automatically. Open the link above.');
+ return 0;
+}
+
+function launchLocal(command: string, runtime: Required<Runtime>): number {
+ const { run, log, platform, env } = runtime;
+ const installing = command === 'npm';
+ const args = installing ? ['install', PACKAGE_SPEC] : [AGENT_PROMPT];
+ log(installing ? `Installing ${PACKAGE_SPEC} in ${process.cwd()}...` : `Starting ${command} in ${process.cwd()}...`);
+ // Windows npm/agent launchers may be .cmd files. Keep the prompt out of shell
+ // syntax by passing it via the child environment to a fixed PowerShell script.
+ const result = platform === 'win32'
+ ? run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
+ `$ErrorActionPreference = 'Stop'; & ${command} ${installing ? `install '${PACKAGE_SPEC}'` : '$env:TRADINGVIEW_QUICK_START_PROMPT'}; exit $LASTEXITCODE`],
+ { stdio: 'inherit', env: { ...env, TRADINGVIEW_QUICK_START_PROMPT: AGENT_PROMPT } })
+ : run(command, args, { stdio: 'inherit', env });
+ if (result.error || result.status !== 0) {
+ if (installing) log(`Installation did not complete. Retry: npm install ${PACKAGE_SPEC}`);
+ else {
+ log(`Could not complete ${command}. Ensure its CLI is installed and authenticated, then retry.`);
+ printPrompt(log);
+ }
+ return result.status ?? (result.signal === 'SIGINT' ? 130 : 1);
+ }
+ if (installing) log('Library installed. Guide: https://github.com/Mathieu2301/TradingView-API/blob/main/docs/data-api.md');
+ return 0;
+}
+
+export function runChoice(choice: string, overrides: Runtime = {}): number {
+ const runtime = { run: spawnSync, log: console.log, platform: process.platform, env: process.env, ...overrides };
+ switch (choice) {
+ case '1': return openLanding(runtime);
+ case '2': return launchLocal('claude', runtime);
+ case '3': return launchLocal('codex', runtime);
+ case '4': printPrompt(runtime.log); return 0;
+ case '5': return launchLocal('npm', runtime);
+ default: runtime.log('Invalid choice. Choose a number from 1 to 5.'); return 1;
+ }
+}
+
+export async function main(args = process.argv.slice(2)): Promise<number> {
+ if (args.length === 1 && ['--help', '-h'].includes(args[0]!)) {
+ console.log(HELP);
+ return 0;
+ }
+ if (args.length) {
+ if (args.length !== 2 || args[0] !== '--choice' || !/^[1-5]$/.test(args[1]!)) {
+ console.error(HELP);
+ return 1;
+ }
+ return runChoice(args[1]!);
+ }
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
+ console.error('Interactive selection requires a terminal. Use --choice 1|2|3|4|5.');
+ return 1;
+ }
+ console.log(HELP);
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
+ const abort = new AbortController();
+ rl.on('SIGINT', () => { abort.abort(); rl.close(); });
+ rl.on('close', () => abort.abort());
+ let choice: string;
+ try {
+ while (true) {
+ choice = (await rl.question('Choose an option [1]: ', { signal: abort.signal })).trim() || '1';
+ if (/^[1-5]$/.test(choice)) break;
+ console.log('Please enter a number from 1 to 5.');
+ }
+ } catch (error) {
+ if (abort.signal.aborted || (error as NodeJS.ErrnoException).code === 'ERR_USE_AFTER_CLOSE') return 130;
+ throw error;
+ } finally {
+ rl.close();
+ }
+ // Release readline before handing the terminal to an interactive agent.
+ return runChoice(choice);
+}
diff --git a/tests/unit/quick-start.test.ts b/tests/unit/quick-start.test.ts
new file mode 100644
index 0000000..49f1722
--- /dev/null
+++ b/tests/unit/quick-start.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest';
+import { AGENT_PROMPT, HELP, LANDING_URL, PACKAGE_SPEC, main, runChoice } from '../../src/quick-start.js';
+
+describe('quick-start', () => {
+ const ok = { status: 0, signal: null, error: undefined };
+ it.each(['linux', 'darwin', 'win32'] as const)('opens the hosted path on %s without installing anything', (platform) => {
+ const commands: string[] = [];
+ const messages: string[] = [];
+ expect(runChoice('1', { platform, log: (s) => messages.push(s), run: (cmd, args) => {
+ commands.push(cmd);
+ expect(args).toContain(LANDING_URL);
+ return ok;
+ } })).toBe(0);
+ expect(commands).toEqual([platform === 'linux' ? 'xdg-open' : platform === 'darwin' ? 'open' : 'rundll32.exe']);
+ expect(messages.join('\n')).toContain(LANDING_URL);
+ });
+ it('leaves a usable link when opening a browser fails', () => {
+ const messages: string[] = [];
+ expect(runChoice('1', { log: (s) => messages.push(s), run: () => ({ ...ok, status: null, error: new Error('ENOENT') }) })).toBe(0);
+ expect(messages.join('\n')).toContain('Open the link above');
+ });
+ it.each([['2', 'claude'], ['3', 'codex']])('hands the prompt to %s as one argument with terminal inheritance', (choice, command) => {
+ expect(runChoice(choice!, { platform: 'linux', log: () => {}, run: (cmd, args, options) => {
+ expect(cmd).toBe(command);
+ expect(args).toEqual([AGENT_PROMPT]);
+ expect(options.stdio).toBe('inherit');
+ expect(options.shell).toBeUndefined();
+ return ok;
+ } })).toBe(0);
+ });
+ it.each(['2', '3', '5'])('uses a fixed Windows launcher for choice %s', (choice) => {
+ expect(runChoice(choice, { platform: 'win32', log: () => {}, run: (cmd, args, options) => {
+ expect(cmd).toBe('powershell.exe');
+ expect(args.join(' ')).not.toContain(AGENT_PROMPT);
+ expect(options.env?.TRADINGVIEW_QUICK_START_PROMPT).toBe(AGENT_PROMPT);
+ expect(args.at(-1)).toContain(choice === '5' ? `install '${PACKAGE_SPEC}'` : '$env:TRADINGVIEW_QUICK_START_PROMPT');
+ return ok;
+ } })).toBe(0);
+ });
+ it('only prints the prompt for another agent', () => {
+ const messages: string[] = [];
+ expect(runChoice('4', { log: (s) => messages.push(s), run: () => { throw new Error('must not spawn'); } })).toBe(0);
+ expect(messages.join('\n')).toContain(AGENT_PROMPT);
+ });
+ it('only installs the V4 next package', () => {
+ expect(runChoice('5', { platform: 'linux', log: () => {}, run: (cmd, args) => {
+ expect(cmd).toBe('npm');
+ expect(args).toEqual(['install', PACKAGE_SPEC]);
+ return ok;
+ } })).toBe(0);
+ });
+ it('preserves a failing child exit status and provides the fallback prompt', () => {
+ const messages: string[] = [];
+ expect(runChoice('2', { log: (s) => messages.push(s), run: () => ({ ...ok, status: 7 }) })).toBe(7);
+ expect(messages.join('\n')).toContain(AGENT_PROMPT);
+ });
+ it('handles a missing CLI and interrupted installation without reporting success', () => {
+ expect(runChoice('3', { log: () => {}, run: () => ({ ...ok, status: null, error: new Error('ENOENT') }) })).toBe(1);
+ const messages: string[] = [];
+ expect(runChoice('5', { log: (s) => messages.push(s), run: () => ({ ...ok, status: null, signal: 'SIGINT' }) })).toBe(130);
+ expect(messages.join('\n')).not.toContain('Library installed');
+ });
+ it('rejects invalid selections without spawning a command', () => {
+ expect(runChoice('6', { log: () => {}, run: () => { throw new Error('must not spawn'); } })).toBe(1);
+ });
+ it('documents all choices and supports help and explicit prompt mode', async () => {
+ expect(HELP).toContain('Autonomous agent (recommended)');
+ expect(await main(['--help'])).toBe(0);
+ expect(await main(['--choice', '4'])).toBe(0);
+ expect(await main(['--choice', '6'])).toBe(1);
+ expect(await main(['--unknown'])).toBe(1);
+ });
+});