diff --git a/README.md b/README.md index a0005d47..1562576f 100644 --- a/README.md +++ b/README.md @@ -1,175 +1,47 @@ -# TradingView-API +# TradingView API [![GitHub stars](https://img.shields.io/github/stars/Mathieu2301/TradingView-API.svg?style=social&label=Star)](https://github.com/Mathieu2301/TradingView-API/stargazers) -**Build with market data, from your first chart to a running watcher.** Fetch candles and quotes, run indicators and strategies, and turn ideas into working tools. An independent community project, not an official TradingView API. - -[Get started](#get-started) · [Explore examples](examples) · [Read the data API guide](docs/data-api.md) - -**Language:** English · [Français](docs/README.fr.md) · [Español](docs/README.es.md) · [Português](docs/README.pt.md) - -[![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) +[![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) +[![CodeFactor](https://www.codefactor.io/repository/github/mathieu2301/tradingview-api/badge/main)](https://www.codefactor.io/repository/github/mathieu2301/tradingview-api/overview/main) +[![npm downloads](https://badgen.net/npm/dt/@mathieuc/tradingview)](https://www.npmjs.com/package/@mathieuc/tradingview) +[![npm version](https://badgen.net/npm/v/@mathieuc/tradingview)](https://www.npmjs.com/package/@mathieuc/tradingview) Mathieu2301/TradingView-API | #1 Repo Of The Day on Trendshift -Film: a trader asks an AI agent to turn a private TradingView indicator into a bot; the agent installs TradingView-API, backtests it and trades it on a demo account - -**Turn your TradingView indicators into a trading bot, just by chatting.** An AI agent on molted installs TradingView-API, backtests your setup and runs it 24/7 on a demo account. Real money only when you say so. - -**[Create my AI agent →](https://molted.studio/dreams/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api)** - -▶ With sound: - -https://github.com/user-attachments/assets/88859255-9e80-435e-95d4-f6f40bf0946b - -### One request, real data - -> **V4 is the default npm release.** Install with `npm install @mathieuc/tradingview` to use `getCandles` and the new data API. - -```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 } -``` - -![Recorded demonstration: a candle request returns 40 daily BTC/USDT candles, visualized as a line chart](assets/readme-demo.gif) +Get realtime market prices, indicator values and backtests from TradingView! 📈 -*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.* +🌐 English · [Français](docs/README.fr.md) · [Español](docs/README.es.md) · [Português](docs/README.pt.md) -Prefer to start without code? The setup paths below work too. +## 🟢 Need help with your project? -> **Version 4 is a breaking rewrite** in TypeScript, with a new API and no compatibility layer. Coming from v3? Read the [migration guide](docs/migration-v4.md). Every v3 feature is still available: see the [coverage matrix](docs/v4-coverage.md) and [reliability evidence](docs/v4-reliability.md). The [RC preparation report](docs/v4-stabilization.md) tracks current checks and remaining release gates. npm versions 3.x keep the previous `Client` API; check the [npm page](https://www.npmjs.com/package/@mathieuc/tradingview) for the version you install. +🚀 **[Click here to get help with your project](https://molted.studio/dreams/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api&utm_content=need-help)** -## Get started +Film: a trader gets help from an AI agent that installs TradingView-API, backtests the setup and runs it on a demo account -### Interactive quick-start +## ✨ Features -The interactive launcher is included in V4: +- ✅ Realtime candles and quotes +- ✅ Indicator values: built-in and Pine indicators, invite-only included (with access) +- ✅ Strategy reports +- ✅ Honest backtests: no look-ahead, fees, random-entry baseline +- ✅ Replay mode + fake replay mode (free plan) +- ✅ Values for a specific date range +- ✅ Screener and hotlists +- ✅ Your watchlists and the drawings on your charts +- ✅ TradingView's technical analysis +- 💡 Want a feature? [Ask here](https://github.com/Mathieu2301/TradingView-API/issues/new/choose) -```bash -npx @mathieuc/tradingview -``` - -Run it from your project directory with Node.js 20+. Choose a path: - -1. **Autonomous agent (recommended)** — opens the [TradingView-API market watcher on Molted Studio](https://molted.studio/dreams/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api). 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` here, without generating files or starting an agent. - -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. - -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: +## 📦 Installation ```bash -npm ci && npm run build -node bin/tradingview.mjs +npm i @mathieuc/tradingview ``` -### Install manually - -```bash -npm install @mathieuc/tradingview -# Or: bun add @mathieuc/tradingview -``` - -V4 is installed by default. V3 remains available with `@mathieuc/tradingview@3`; read the migration guide before upgrading existing V3 projects. - -The V4 package is ESM with TypeScript declarations. CommonJS projects can `require()` it on Node 20.19+ or 22.12+, or use `await import()`. - -### Want to contribute? - -[Open an issue](https://github.com/Mathieu2301/TradingView-API/issues/new/choose) to discuss a feature or report a bug, or send a pull request. Questions and early ideas are welcome; you do not need a perfect reproduction to start a conversation. `npm run check` runs the type check, lint, tests, build and package smoke test. - -## Data API - -The data API handles connections, sessions, timeouts and cleanup for you. It suits any application: scripts, servers, dashboards, bots or agents. - -```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: (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 }, -}); -``` - -| Need | Function | -| --- | --- | -| Candles: latest bars, deep history, date ranges, Heikin Ashi/Renko/... | `getCandles`, `watchCandles` | -| Quotes: last price, change, bid/ask, volume... | `getQuote`, `getQuotes`, `watchQuotes` | -| Indicator values, drawings and strategy reports | `getIndicatorData`, `watchIndicator` | -| Symbol metadata | `getSymbolInfo` | -| Stock/crypto screening and ranked lists | `getScreener`, `getHotlist` | -| Account watchlists (read-only) | `getWatchlists` | -| Search and ratings | `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis` | - -Websocket data functions accept `timeoutMs`, an `AbortSignal`, account `credentials`, and an optional shared `client`. HTTP lookups accept an `AbortSignal` through their options. Errors are `TradingViewError`s with a `code` such as `SYMBOL_ERROR`, `TIMEOUT` or `STUDY_ERROR`. Read the [data API guide](docs/data-api.md) for every option. - -## Backtest API - -Write the entry rule; `@mathieuc/tradingview/backtest` does the rest: frozen candles, look-ahead rejection, entry at the next open, fees and slippage on both sides, pessimistic fills, in-sample/out-of-sample split, four exits and a seeded random-entry baseline. - -```ts -import { backtest, formatReport, rsiDivergence } from '@mathieuc/tradingview/backtest'; - -const { report } = await backtest({ - symbol: 'BINANCE:BTCUSDT', timeframe: '240', years: 2, - signal: rsiDivergence(), // Or your own: (candles) => [{ bar, direction: 'long' | 'short' }] -}); -console.log(formatReport(report)); // report is plain JSON: rows per exit and split, trades, warnings -``` - -It makes no claim of profitability: a negative or inconclusive result is a valid outcome. Read the [backtest guide](docs/backtest.md). - -## Low-level API - -For full control (several charts and studies on one connection, replay mode, raw packets), use the client and sessions directly: - -```ts -import { TradingViewClient, getIndicator } from '@mathieuc/tradingview'; - -const client = new TradingViewClient({ credentials: { session, signature } }); // Credentials are optional -const chart = client.createChart(); - -chart.on('update', () => console.log(chart.lastCandle?.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(); -``` - -The [low-level API reference](docs/low-level-api.md) covers charts, replay, studies, quotes, account and layout functions, Pine permissions, custom transports and protocol helpers. The [examples](examples) show each feature. - -## Accounts and limits +📚 [Getting started](docs/getting-started.md) · [Data API](docs/data-api.md) · [Backtest](docs/backtest.md) · [Low-level API](docs/low-level-api.md) · [Examples](examples) -Without an account, TradingView serves limited data: shorter intraday history, no Pine studies, and possibly delayed or substitute feeds. With your `sessionid` and `sessionid_sign` cookies (`credentials`), you get what your account can access. Keep them in environment variables or a secret store; never put them in source files, issues or prompts. +## 🐛 Problems -## Project links +If you have errors or unwanted behavior, please [open an issue](https://github.com/Mathieu2301/TradingView-API/issues/new/choose). -- [GitHub repository](https://github.com/Mathieu2301/TradingView-API) -- [Trendshift community highlight](https://trendshift.io/repositories/26416) -- [npm package](https://www.npmjs.com/package/@mathieuc/tradingview) -- [Examples](examples) -- [Report a bug or ask for a feature](https://github.com/Mathieu2301/TradingView-API/issues/new/choose) +___ -TradingView is a trademark of its respective owner. This project is not affiliated with or endorsed by TradingView. Check your data provider's terms and applicable market-data permissions for your use case. +Independent community project. TradingView is a trademark of its respective owner; this project is not affiliated with or endorsed by TradingView. diff --git a/assets/readme-demo.gif b/assets/readme-demo.gif deleted file mode 100644 index 103e220e..00000000 Binary files a/assets/readme-demo.gif and /dev/null differ diff --git a/docs/README.es.md b/docs/README.es.md index ac3f8a70..e14176c7 100644 --- a/docs/README.es.md +++ b/docs/README.es.md @@ -1,175 +1,47 @@ -# TradingView-API +# TradingView API [![GitHub stars](https://img.shields.io/github/stars/Mathieu2301/TradingView-API.svg?style=social&label=Star)](https://github.com/Mathieu2301/TradingView-API/stargazers) -**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. - -[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) - -[![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) +[![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) +[![CodeFactor](https://www.codefactor.io/repository/github/mathieu2301/tradingview-api/badge/main)](https://www.codefactor.io/repository/github/mathieu2301/tradingview-api/overview/main) +[![npm downloads](https://badgen.net/npm/dt/@mathieuc/tradingview)](https://www.npmjs.com/package/@mathieuc/tradingview) +[![npm version](https://badgen.net/npm/v/@mathieuc/tradingview)](https://www.npmjs.com/package/@mathieuc/tradingview) Mathieu2301/TradingView-API | #1 Repo Of The Day on Trendshift -Película: un trader pide a un agente de IA que convierta su indicador privado de TradingView en un bot; el agente instala TradingView-API, lo prueba con datos históricos y opera en una cuenta demo - -**Convierte tus indicadores de TradingView en un bot de trading, solo conversando.** Un agente de IA en molted instala TradingView-API, prueba tu estrategia con datos históricos y la ejecuta 24/7 en una cuenta demo. Dinero real solo cuando tú lo decidas. - -**[Crear mi agente de IA →](https://molted.studio/dreams/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api)** - -▶ Con sonido (en inglés): - -https://github.com/user-attachments/assets/88859255-9e80-435e-95d4-f6f40bf0946b - -### Una consulta, datos reales - -> **V4 es la versión predeterminada en npm.** Instálala con `npm install @mathieuc/tradingview` para usar `getCandles` y la nueva API de datos. - -```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 } -``` - -![Demostración grabada: una consulta devuelve 40 velas diarias de BTC/USDT, representadas como un gráfico de líneas](../assets/readme-demo.gif) +¡Obtén precios en tiempo real, valores de indicadores y backtests desde TradingView! 📈 -*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.* +🌐 [English](../README.md) · [Français](README.fr.md) · Español · [Português](README.pt.md) -¿Prefieres empezar sin código? También puedes usar las opciones de abajo. +## 🟢 ¿Necesitas ayuda con tu proyecto? -> **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. +🚀 **[Haz clic aquí para recibir ayuda con tu proyecto](https://molted.studio/dreams/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api&utm_content=need-help)** -## Primeros pasos +Película: un trader recibe ayuda de un agente de IA que instala TradingView-API, prueba su estrategia con datos históricos y la ejecuta en una cuenta demo -### Inicio rápido interactivo +## ✨ Funcionalidades -El asistente interactivo está incluido en la V4: +- ✅ Velas y cotizaciones en tiempo real +- ✅ Valores de indicadores: integrados y Pine, incluidos los de invitación (con acceso) +- ✅ Informes de estrategia +- ✅ Backtests honestos: sin anticipación, con comisiones y comparación con entradas al azar +- ✅ Modo replay + replay simulado (plan gratuito) +- ✅ Valores en un rango de fechas concreto +- ✅ Screener y rankings +- ✅ Tus listas de seguimiento y los dibujos de tus gráficos +- ✅ El análisis técnico de TradingView +- 💡 ¿Te falta una funcionalidad? [Pídela aquí](https://github.com/Mathieu2301/TradingView-API/issues/new/choose) -```bash -npx @mathieuc/tradingview -``` - -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/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api). 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` 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: +## 📦 Instalación ```bash -npm ci && npm run build -node bin/tradingview.mjs +npm i @mathieuc/tradingview ``` -### Instalación manual - -```bash -npm install @mathieuc/tradingview -# O: bun add @mathieuc/tradingview -``` - -V4 se instala por defecto. V3 sigue disponible con `@mathieuc/tradingview@3`; consulta la guía de migración antes de actualizar un proyecto 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 - -La API de datos gestiona las conexiones, las sesiones, los tiempos de espera y la limpieza. Sirve para scripts, servidores, paneles, bots y agentes. - -```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: (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 }, -}); -``` - -| 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 backtest - -Escribe la regla de entrada; `@mathieuc/tradingview/backtest` hace el resto: velas congeladas, rechazo de la anticipación (look-ahead), entrada en la apertura siguiente, comisiones y slippage en ambos lados, ejecuciones pesimistas, división in-sample/out-of-sample, cuatro salidas y una referencia de entradas aleatorias con semilla. - -```ts -import { backtest, formatReport, rsiDivergence } from '@mathieuc/tradingview/backtest'; - -const { report } = await backtest({ - symbol: 'BINANCE:BTCUSDT', timeframe: '240', years: 2, - signal: rsiDivergence(), // O la tuya: (candles) => [{ bar, direction: 'long' | 'short' }] -}); -console.log(formatReport(report)); // report es JSON simple: filas por salida y segmento, operaciones, avisos -``` - -No promete ninguna rentabilidad: un resultado negativo o no concluyente es un resultado válido. Lee la [guía de backtest](backtest.md) (en inglés). - -## 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, getIndicator } from '@mathieuc/tradingview'; - -const client = new TradingViewClient({ credentials: { session, signature } }); // Credentials are optional -const chart = client.createChart(); - -chart.on('update', () => console.log(chart.lastCandle?.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(); -``` - -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 +📚 [Primeros pasos](getting-started.md) · [API de datos](data-api.md) · [Backtest](backtest.md) · [API de bajo nivel](low-level-api.md) · [Ejemplos](../examples) (guías en inglés) -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. +## 🐛 Problemas -## Enlaces del proyecto +Si tienes errores o un comportamiento inesperado, [abre una issue](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 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. +Proyecto comunitario independiente. TradingView es una marca de su propietario; este proyecto no está afiliado ni respaldado por TradingView. diff --git a/docs/README.fr.md b/docs/README.fr.md index c78964d9..9d0e7121 100644 --- a/docs/README.fr.md +++ b/docs/README.fr.md @@ -1,171 +1,47 @@ -# TradingView-API +# TradingView API [![GitHub stars](https://img.shields.io/github/stars/Mathieu2301/TradingView-API.svg?style=social&label=Star)](https://github.com/Mathieu2301/TradingView-API/stargazers) -**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. - -[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) - -[![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) +[![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) +[![CodeFactor](https://www.codefactor.io/repository/github/mathieu2301/tradingview-api/badge/main)](https://www.codefactor.io/repository/github/mathieu2301/tradingview-api/overview/main) +[![npm downloads](https://badgen.net/npm/dt/@mathieuc/tradingview)](https://www.npmjs.com/package/@mathieuc/tradingview) +[![npm version](https://badgen.net/npm/v/@mathieuc/tradingview)](https://www.npmjs.com/package/@mathieuc/tradingview) Mathieu2301/TradingView-API | #1 Repo Of The Day on Trendshift -Film : un trader demande à un agent IA de transformer son indicateur TradingView privé en bot ; l’agent installe TradingView-API, le backteste et le fait trader sur un compte démo - -**Transformez vos indicateurs TradingView en bot de trading, simplement en discutant.** Un agent IA sur molted installe TradingView-API, backteste votre setup et le fait tourner 24 h/24 sur un compte démo. L’argent réel, seulement quand vous le décidez. +Récupérez les prix en temps réel, les valeurs d’indicateurs et des backtests depuis TradingView ! 📈 -**[▶ Voir le film avec le son](https://molted.studio/fr/dreams/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api#film)** · **[Créer mon agent IA →](https://molted.studio/fr/dreams/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api)** +🌐 [English](../README.md) · Français · [Español](README.es.md) · [Português](README.pt.md) -### Une requête, de vraies données +## 🟢 Besoin d’aide sur votre projet ? -> **La V4 est la version npm par défaut.** Installez-la avec `npm install @mathieuc/tradingview` pour utiliser `getCandles` et la nouvelle API de données. - -```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 } -``` +🚀 **[Cliquez ici pour obtenir de l’aide sur votre projet](https://molted.studio/fr/dreams/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api&utm_content=need-help)** -![Démonstration enregistrée : une requête renvoie 40 bougies quotidiennes BTC/USDT, représentées en courbe](../assets/readme-demo.gif) +Film : un trader se fait aider par un agent IA qui installe TradingView-API, backteste sa stratégie et la fait tourner sur un compte démo -*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.* +## ✨ Fonctionnalités -Vous préférez commencer sans coder ? Les parcours ci-dessous le permettent aussi. +- ✅ Bougies et cotations en temps réel +- ✅ Valeurs d’indicateurs : intégrés et Pine, y compris sur invitation (avec accès) +- ✅ Rapports de stratégie +- ✅ Backtests honnêtes : sans anticipation, avec frais et comparaison au hasard +- ✅ Mode replay + faux replay (offre gratuite) +- ✅ Valeurs sur une plage de dates précise +- ✅ Screener et palmarès +- ✅ Vos listes de suivi et les dessins de vos graphiques +- ✅ L’analyse technique de TradingView +- 💡 Une fonctionnalité vous manque ? [Demandez ici](https://github.com/Mathieu2301/TradingView-API/issues/new/choose) -> **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. - -## Démarrer - -### Quick-start interactif - -Le lanceur interactif est inclus dans la V4 : +## 📦 Installation ```bash -npx @mathieuc/tradingview +npm i @mathieuc/tradingview ``` -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/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api). 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` 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 : - -```bash -npm ci && npm run build -node bin/tradingview.mjs -``` - -### Installation manuelle - -```bash -npm install @mathieuc/tradingview -# Ou : bun add @mathieuc/tradingview -``` - -La V4 est installée par défaut. La V3 reste disponible avec `@mathieuc/tradingview@3` ; consultez le guide de migration avant de mettre à jour un projet 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 - -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. - -```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: (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 }, -}); -``` - -| 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 de backtest - -Écrivez la règle d’entrée ; `@mathieuc/tradingview/backtest` fait le reste : bougies figées, rejet de l’anticipation (look-ahead), entrée à l’ouverture suivante, frais et slippage aux deux bouts, exécutions pessimistes, séparation in-sample/out-of-sample, quatre sorties et une référence d’entrées aléatoires seedées. - -```ts -import { backtest, formatReport, rsiDivergence } from '@mathieuc/tradingview/backtest'; - -const { report } = await backtest({ - symbol: 'BINANCE:BTCUSDT', timeframe: '240', years: 2, - signal: rsiDivergence(), // Ou la vôtre : (candles) => [{ bar, direction: 'long' | 'short' }] -}); -console.log(formatReport(report)); // report est du JSON simple : lignes par sortie et segment, trades, avertissements -``` - -Il ne promet aucune rentabilité : un résultat négatif ou non concluant est un résultat valable. Lire le [guide du backtest](backtest.md) (en anglais). - -## 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, getIndicator } from '@mathieuc/tradingview'; - -const client = new TradingViewClient({ credentials: { session, signature } }); // Credentials are optional -const chart = client.createChart(); - -chart.on('update', () => console.log(chart.lastCandle?.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(); -``` - -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 +📚 [Démarrer](getting-started.md) · [API de données](data-api.md) · [Backtest](backtest.md) · [API bas niveau](low-level-api.md) · [Exemples](../examples) (guides en anglais) -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. +## 🐛 Problèmes -## Liens du projet +En cas d’erreur ou de comportement inattendu, [ouvrez une issue](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é à TradingView ni approuvé par TradingView. Vérifiez les conditions de votre fournisseur de données et les autorisations applicables à votre usage. +Projet communautaire indépendant. TradingView est une marque de son propriétaire ; ce projet n’est ni affilié ni approuvé par TradingView. diff --git a/docs/README.pt.md b/docs/README.pt.md index 90271113..8e5d52da 100644 --- a/docs/README.pt.md +++ b/docs/README.pt.md @@ -1,175 +1,47 @@ -# TradingView-API +# TradingView API [![GitHub stars](https://img.shields.io/github/stars/Mathieu2301/TradingView-API.svg?style=social&label=Star)](https://github.com/Mathieu2301/TradingView-API/stargazers) -**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. - -[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 - -[![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) +[![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) +[![CodeFactor](https://www.codefactor.io/repository/github/mathieu2301/tradingview-api/badge/main)](https://www.codefactor.io/repository/github/mathieu2301/tradingview-api/overview/main) +[![npm downloads](https://badgen.net/npm/dt/@mathieuc/tradingview)](https://www.npmjs.com/package/@mathieuc/tradingview) +[![npm version](https://badgen.net/npm/v/@mathieuc/tradingview)](https://www.npmjs.com/package/@mathieuc/tradingview) Mathieu2301/TradingView-API | #1 Repo Of The Day on Trendshift -Filme: um trader pede a um agente de IA que transforme seu indicador privado do TradingView em um bot; o agente instala a TradingView-API, faz o backtest e opera em uma conta demo - -**Transforme seus indicadores do TradingView em um bot de trading, só conversando.** Um agente de IA na molted instala a TradingView-API, faz o backtest da sua estratégia e a executa 24/7 em uma conta demo. Dinheiro real só quando você decidir. - -**[Criar meu agente de IA →](https://molted.studio/dreams/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api)** - -▶ Com som (em inglês): - -https://github.com/user-attachments/assets/88859255-9e80-435e-95d4-f6f40bf0946b - -### Uma consulta, dados reais - -> **A V4 é a versão padrão no npm.** Instale com `npm install @mathieuc/tradingview` para usar `getCandles` e a nova API de dados. - -```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 } -``` - -![Demonstração gravada: uma consulta retorna 40 candles diários de BTC/USDT, exibidos em um gráfico de linhas](../assets/readme-demo.gif) +Obtenha preços em tempo real, valores de indicadores e backtests do TradingView! 📈 -*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.* +🌐 [English](../README.md) · [Français](README.fr.md) · [Español](README.es.md) · Português -Prefere começar sem código? Os caminhos abaixo também funcionam. +## 🟢 Precisa de ajuda com seu projeto? -> **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. +🚀 **[Clique aqui para receber ajuda com seu projeto](https://molted.studio/dreams/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api&utm_content=need-help)** -## Primeiros passos +Filme: um trader recebe ajuda de um agente de IA que instala a TradingView-API, faz o backtest da estratégia e a executa em uma conta demo -### Início rápido interativo +## ✨ Funcionalidades -O assistente interativo está incluído na V4: +- ✅ Candles e cotações em tempo real +- ✅ Valores de indicadores: nativos e Pine, inclusive os de convite (com acesso) +- ✅ Relatórios de estratégia +- ✅ Backtests honestos: sem antecipação, com taxas e comparação com entradas aleatórias +- ✅ Modo replay + replay simulado (plano gratuito) +- ✅ Valores em um intervalo de datas específico +- ✅ Screener e rankings +- ✅ Suas listas de observação e os desenhos dos seus gráficos +- ✅ A análise técnica do TradingView +- 💡 Falta alguma funcionalidade? [Peça aqui](https://github.com/Mathieu2301/TradingView-API/issues/new/choose) -```bash -npx @mathieuc/tradingview -``` - -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/ai-agent-for-tradingview-data?utm_source=github&utm_medium=readme&utm_campaign=tradingview-api). 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` 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 localmente: +## 📦 Instalação ```bash -npm ci && npm run build -node bin/tradingview.mjs +npm i @mathieuc/tradingview ``` -### Instalação manual - -```bash -npm install @mathieuc/tradingview -# Ou: bun add @mathieuc/tradingview -``` - -A V4 é instalada por padrão. A V3 continua disponível com `@mathieuc/tradingview@3`; consulte o guia de migração antes de atualizar um projeto 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 - -A API de dados gerencia conexões, sessões, tempos limite e limpeza para você. É adequada para scripts, servidores, painéis, bots e agentes. - -```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: (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 }, -}); -``` - -| 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 backtest - -Escreva a regra de entrada; `@mathieuc/tradingview/backtest` faz o resto: velas congeladas, rejeição de antecipação (look-ahead), entrada na abertura seguinte, taxas e slippage nas duas pontas, execuções pessimistas, divisão in-sample/out-of-sample, quatro saídas e uma referência de entradas aleatórias com semente. - -```ts -import { backtest, formatReport, rsiDivergence } from '@mathieuc/tradingview/backtest'; - -const { report } = await backtest({ - symbol: 'BINANCE:BTCUSDT', timeframe: '240', years: 2, - signal: rsiDivergence(), // Ou a sua: (candles) => [{ bar, direction: 'long' | 'short' }] -}); -console.log(formatReport(report)); // report é JSON simples: linhas por saída e segmento, trades, avisos -``` - -Não promete nenhuma rentabilidade: um resultado negativo ou inconclusivo é um resultado válido. Leia o [guia de backtest](backtest.md) (em inglês). - -## 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, getIndicator } from '@mathieuc/tradingview'; - -const client = new TradingViewClient({ credentials: { session, signature } }); // Credentials are optional -const chart = client.createChart(); - -chart.on('update', () => console.log(chart.lastCandle?.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(); -``` - -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 +📚 [Primeiros passos](getting-started.md) · [API de dados](data-api.md) · [Backtest](backtest.md) · [API de baixo nível](low-level-api.md) · [Exemplos](../examples) (guias em inglês) -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. +## 🐛 Problemas -## Links do projeto +Se tiver erros ou um comportamento inesperado, [abra uma issue](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 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. +Projeto comunitário independente. TradingView é uma marca de seu proprietário; este projeto não é afiliado nem endossado pelo TradingView. diff --git a/docs/backtest.md b/docs/backtest.md index 0b94d071..b35778e8 100644 --- a/docs/backtest.md +++ b/docs/backtest.md @@ -22,7 +22,7 @@ writeFileSync('trades.csv', tradesToCsv(report.trades)); writeFileSync('snapshot.json', JSON.stringify(snapshot)); // Replay later, exactly ``` -No account is needed for public symbols. With `credentials`, history goes as far as the account allows (see [Accounts and limits](../README.md#accounts-and-limits)). After the download, the reference strategy on about 4 500 4H bars (4 exits × 2 splits × 1 000 random runs) runs in about 0.2 s; a rule with a thousand signals takes about 10 s, mostly in the random baseline (lower `runs` while iterating). +No account is needed for public symbols. With `credentials`, history goes as far as the account allows (see [Accounts and limits](getting-started.md#accounts-and-limits)). After the download, the reference strategy on about 4 500 4H bars (4 exits × 2 splits × 1 000 random runs) runs in about 0.2 s; a rule with a thousand signals takes about 10 s, mostly in the random baseline (lower `runs` while iterating). ## Writing the signal diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 00000000..a32c6b56 --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,52 @@ +# Getting started + +## Install + +```bash +npm install @mathieuc/tradingview +# Or: bun add @mathieuc/tradingview +``` + +Version 4 is installed by default: TypeScript, ESM, Node.js 20+ or Bun. CommonJS projects can `require()` it on Node 20.19+ or 22.12+, or use `await import()`. Version 3 remains available with `@mathieuc/tradingview@3`. + +> **Version 4 is a breaking rewrite**, with a new API and no compatibility layer. Coming from v3? Read the [migration guide](migration-v4.md). Every v3 feature is still available: see the [coverage matrix](v4-coverage.md) and the [reliability evidence](v4-reliability.md). + +```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 } +``` + +Then read the [data API guide](data-api.md), the [backtest guide](backtest.md), the [low-level API reference](low-level-api.md) or the [examples](../examples). + +## Interactive quick-start + +```bash +npx @mathieuc/tradingview +``` + +Run it from your project directory with Node.js 20+. Choose a path: + +1. **Autonomous agent (recommended)** — opens the [TradingView-API page on molted.studio](https://molted.studio/dreams/ai-agent-for-tradingview-data?utm_source=github&utm_medium=docs&utm_campaign=tradingview-api). 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` here, without generating files or starting an agent. + +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. + +Use `--choice 4` to print the prompt directly, or `--help` for usage. Non-interactive callers must pass `--choice`. To try the launcher from a checkout: + +```bash +npm ci && npm run build +node bin/tradingview.mjs +``` + +## Accounts and limits + +Without an account, TradingView serves limited data: shorter intraday history, no Pine studies, and possibly delayed or substitute feeds. With your `sessionid` and `sessionid_sign` cookies (`credentials`), you get what your account can access. Keep them in environment variables or a secret store; never put them in source files, issues or prompts. + +## Contributing + +[Open an issue](https://github.com/Mathieu2301/TradingView-API/issues/new/choose) to discuss a feature or report a bug, or send a pull request. Questions and early ideas are welcome; you do not need a perfect reproduction to start a conversation. `npm run check` runs the type check, lint, tests, build and package smoke test.