@mathieuc/tradingview 3.5.2 → 4.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +112 -51
  2. package/dist/chart/chart-session.d.ts +114 -0
  3. package/dist/chart/chart-session.js +339 -0
  4. package/dist/chart/graphics.d.ts +129 -0
  5. package/dist/chart/graphics.js +153 -0
  6. package/dist/chart/index.d.ts +11 -0
  7. package/dist/chart/index.js +6 -0
  8. package/dist/chart/strategy.d.ts +113 -0
  9. package/dist/chart/strategy.js +78 -0
  10. package/dist/chart/study.d.ts +60 -0
  11. package/dist/chart/study.js +179 -0
  12. package/dist/chart/timeframes.d.ts +7 -0
  13. package/dist/chart/timeframes.js +22 -0
  14. package/dist/chart/types.d.ts +105 -0
  15. package/dist/chart/types.js +9 -0
  16. package/dist/client/client.d.ts +89 -0
  17. package/dist/client/client.js +254 -0
  18. package/dist/client/index.d.ts +4 -0
  19. package/dist/client/index.js +2 -0
  20. package/dist/client/transport.d.ts +27 -0
  21. package/dist/client/transport.js +38 -0
  22. package/dist/data/candles.d.ts +40 -0
  23. package/dist/data/candles.js +101 -0
  24. package/dist/data/history.d.ts +61 -0
  25. package/dist/data/history.js +101 -0
  26. package/dist/data/index.d.ts +30 -0
  27. package/dist/data/index.js +16 -0
  28. package/dist/data/indicators.d.ts +54 -0
  29. package/dist/data/indicators.js +139 -0
  30. package/dist/data/operation.d.ts +71 -0
  31. package/dist/data/operation.js +205 -0
  32. package/dist/data/provider.d.ts +23 -0
  33. package/dist/data/provider.js +11 -0
  34. package/dist/data/quotes.d.ts +33 -0
  35. package/dist/data/quotes.js +117 -0
  36. package/dist/data/symbols.d.ts +9 -0
  37. package/dist/data/symbols.js +19 -0
  38. package/dist/errors.d.ts +53 -0
  39. package/dist/errors.js +24 -0
  40. package/dist/events.d.ts +36 -0
  41. package/dist/events.js +70 -0
  42. package/dist/http/account.d.ts +47 -0
  43. package/dist/http/account.js +127 -0
  44. package/dist/http/index.d.ts +11 -0
  45. package/dist/http/index.js +5 -0
  46. package/dist/http/indicators.d.ts +37 -0
  47. package/dist/http/indicators.js +144 -0
  48. package/dist/http/layouts.d.ts +36 -0
  49. package/dist/http/layouts.js +24 -0
  50. package/dist/http/market.d.ts +45 -0
  51. package/dist/http/market.js +59 -0
  52. package/dist/http/pine-permissions.d.ts +29 -0
  53. package/dist/http/pine-permissions.js +56 -0
  54. package/dist/http/request.d.ts +44 -0
  55. package/dist/http/request.js +83 -0
  56. package/dist/index.d.ts +21 -0
  57. package/dist/index.js +19 -0
  58. package/dist/indicators/builtin-indicator.d.ts +17 -0
  59. package/dist/indicators/builtin-indicator.js +75 -0
  60. package/dist/indicators/index.d.ts +8 -0
  61. package/dist/indicators/index.js +2 -0
  62. package/dist/indicators/pine-indicator.d.ts +63 -0
  63. package/dist/indicators/pine-indicator.js +101 -0
  64. package/dist/protocol/compression.d.ts +12 -0
  65. package/dist/protocol/compression.js +83 -0
  66. package/dist/protocol/framing.d.ts +59 -0
  67. package/dist/protocol/framing.js +68 -0
  68. package/dist/protocol/ids.d.ts +2 -0
  69. package/dist/protocol/ids.js +10 -0
  70. package/dist/protocol/index.d.ts +4 -0
  71. package/dist/protocol/index.js +3 -0
  72. package/dist/quote/fields.d.ts +35 -0
  73. package/dist/quote/fields.js +21 -0
  74. package/dist/quote/index.d.ts +4 -0
  75. package/dist/quote/index.js +2 -0
  76. package/dist/quote/quote-session.d.ts +73 -0
  77. package/dist/quote/quote-session.js +205 -0
  78. package/docs/README.es.md +58 -0
  79. package/docs/README.fr.md +58 -0
  80. package/docs/README.pt.md +58 -0
  81. package/docs/data-api.md +285 -0
  82. package/docs/low-level-api.md +213 -0
  83. package/docs/migration-v4.md +128 -0
  84. package/docs/release-4.0.0-beta.1.md +39 -0
  85. package/docs/v4-coverage.md +213 -0
  86. package/package.json +53 -20
  87. package/.env.sample +0 -2
  88. package/.eslintrc.js +0 -28
  89. package/.gitattributes +0 -2
  90. package/docs/DOCS.md +0 -3
  91. package/examples/AllPrivateIndicators.js +0 -44
  92. package/examples/BuiltInIndicator.js +0 -51
  93. package/examples/CustomChartType.js +0 -123
  94. package/examples/CustomTimeframe.js +0 -31
  95. package/examples/Errors.js +0 -155
  96. package/examples/FakeReplayMode.js +0 -40
  97. package/examples/FromToData.js +0 -35
  98. package/examples/GetDrawings.js +0 -27
  99. package/examples/GraphicIndicator.js +0 -42
  100. package/examples/MultipleSyncFetch.js +0 -44
  101. package/examples/PinePermManage.js +0 -67
  102. package/examples/ReplayMode.js +0 -103
  103. package/examples/Search.js +0 -14
  104. package/examples/SimpleChart.js +0 -63
  105. package/examples/UserLogin.js +0 -16
  106. package/main.js +0 -11
  107. package/src/chart/graphicParser.js +0 -308
  108. package/src/chart/session.js +0 -553
  109. package/src/chart/study.js +0 -435
  110. package/src/classes/BuiltInIndicator.js +0 -137
  111. package/src/classes/PineIndicator.js +0 -132
  112. package/src/classes/PinePermManager.js +0 -159
  113. package/src/client.js +0 -298
  114. package/src/miscRequests.js +0 -609
  115. package/src/protocol.js +0 -60
  116. package/src/quote/market.js +0 -132
  117. package/src/quote/session.js +0 -125
  118. package/src/types.js +0 -36
  119. package/src/utils.js +0 -20
  120. package/vite.config.js +0 -7
@@ -0,0 +1,10 @@
1
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
2
+ /** Creates a random session or request ID such as `cs_Ab12Cd34Ef56`. */
3
+ export function createSessionId(prefix = 'xs') {
4
+ const bytes = new Uint8Array(12);
5
+ globalThis.crypto.getRandomValues(bytes);
6
+ let id = '';
7
+ for (const byte of bytes)
8
+ id += ALPHABET[byte % ALPHABET.length];
9
+ return `${prefix}_${id}`;
10
+ }
@@ -0,0 +1,4 @@
1
+ export { decodeFrames, encodeFrame, encodeHeartbeat, encodePacket, } from './framing.js';
2
+ export type { Frame, ServerHello, ServerPacket } from './framing.js';
3
+ export { decodeCompressed, normaliseBase64, readFirstZipEntry } from './compression.js';
4
+ export { createSessionId } from './ids.js';
@@ -0,0 +1,3 @@
1
+ export { decodeFrames, encodeFrame, encodeHeartbeat, encodePacket, } from './framing.js';
2
+ export { decodeCompressed, normaliseBase64, readFirstZipEntry } from './compression.js';
3
+ export { createSessionId } from './ids.js';
@@ -0,0 +1,35 @@
1
+ /** Quote fields TradingView can stream. Other field names are accepted too. */
2
+ export type QuoteField = 'base-currency-logoid' | 'ch' | 'chp' | 'currency-logoid' | 'provider_id' | 'currency_code' | 'current_session' | 'description' | 'exchange' | 'format' | 'fractional' | 'is_tradable' | 'language' | 'local_description' | 'logoid' | 'lp' | 'lp_time' | 'minmov' | 'minmove2' | 'original_name' | 'pricescale' | 'pro_name' | 'short_name' | 'type' | 'update_mode' | 'volume' | 'ask' | 'bid' | 'fundamentals' | 'high_price' | 'low_price' | 'open_price' | 'prev_close_price' | 'rch' | 'rchp' | 'rtc' | 'rtc_time' | 'status' | 'industry' | 'basic_eps_net_income' | 'beta_1_year' | 'market_cap_basic' | 'earnings_per_share_basic_ttm' | 'price_earnings_ttm' | 'sector' | 'dividends_yield' | 'timezone' | 'country_code' | (string & {});
3
+ /** `all` requests every known field, `price` only the last price (`lp`). */
4
+ export type QuoteFieldPreset = 'all' | 'price';
5
+ export declare const ALL_QUOTE_FIELDS: readonly QuoteField[];
6
+ /** Resolves a preset or explicit list into field names. */
7
+ export declare function resolveQuoteFields(fields?: QuoteFieldPreset | readonly QuoteField[]): QuoteField[];
8
+ /**
9
+ * Latest quote values. Only requested fields that TradingView sent are
10
+ * present; numbers are raw server values.
11
+ */
12
+ export interface QuoteData {
13
+ /** Last price. */
14
+ lp?: number;
15
+ /** Time of the last price (Unix seconds). */
16
+ lp_time?: number;
17
+ /** Change since previous close. */
18
+ ch?: number;
19
+ /** Change since previous close, in percent. */
20
+ chp?: number;
21
+ bid?: number;
22
+ ask?: number;
23
+ volume?: number;
24
+ open_price?: number;
25
+ high_price?: number;
26
+ low_price?: number;
27
+ prev_close_price?: number;
28
+ description?: string;
29
+ short_name?: string;
30
+ pro_name?: string;
31
+ exchange?: string;
32
+ currency_code?: string;
33
+ type?: string;
34
+ [field: string]: unknown;
35
+ }
@@ -0,0 +1,21 @@
1
+ export const ALL_QUOTE_FIELDS = [
2
+ 'base-currency-logoid', 'ch', 'chp', 'currency-logoid',
3
+ 'currency_code', 'current_session', 'description',
4
+ 'exchange', 'format', 'fractional', 'is_tradable',
5
+ 'language', 'local_description', 'logoid', 'lp',
6
+ 'lp_time', 'minmov', 'minmove2', 'original_name',
7
+ 'pricescale', 'pro_name', 'short_name', 'type',
8
+ 'update_mode', 'volume', 'ask', 'bid', 'fundamentals',
9
+ 'high_price', 'low_price', 'open_price', 'prev_close_price',
10
+ 'rch', 'rchp', 'rtc', 'rtc_time', 'status', 'industry',
11
+ 'basic_eps_net_income', 'beta_1_year', 'market_cap_basic',
12
+ 'earnings_per_share_basic_ttm', 'price_earnings_ttm',
13
+ 'sector', 'dividends_yield', 'timezone', 'country_code',
14
+ 'provider_id',
15
+ ];
16
+ /** Resolves a preset or explicit list into field names. */
17
+ export function resolveQuoteFields(fields = 'all') {
18
+ if (Array.isArray(fields))
19
+ return fields.length ? [...fields] : [...ALL_QUOTE_FIELDS];
20
+ return fields === 'price' ? ['lp'] : [...ALL_QUOTE_FIELDS];
21
+ }
@@ -0,0 +1,4 @@
1
+ export { QuoteSession, QuoteSubscription, quoteSymbolKey } from './quote-session.js';
2
+ export type { QuoteSessionEvents, QuoteSessionOptions, QuoteSubscriptionEvents, QuoteSubscriptionOptions, } from './quote-session.js';
3
+ export { ALL_QUOTE_FIELDS, resolveQuoteFields } from './fields.js';
4
+ export type { QuoteData, QuoteField, QuoteFieldPreset } from './fields.js';
@@ -0,0 +1,2 @@
1
+ export { QuoteSession, QuoteSubscription, quoteSymbolKey } from './quote-session.js';
2
+ export { ALL_QUOTE_FIELDS, resolveQuoteFields } from './fields.js';
@@ -0,0 +1,73 @@
1
+ import type { TradingViewClient } from '../client/client.js';
2
+ import { TradingViewError } from '../errors.js';
3
+ import { Emitter } from '../events.js';
4
+ import type { TradingSession } from '../chart/types.js';
5
+ import type { ServerPacket } from '../protocol/framing.js';
6
+ import { type QuoteData, type QuoteField, type QuoteFieldPreset } from './fields.js';
7
+ export interface QuoteSessionOptions {
8
+ /** `all` (default), `price`, or an explicit list of fields. */
9
+ fields?: QuoteFieldPreset | readonly QuoteField[];
10
+ }
11
+ export interface QuoteSubscriptionOptions {
12
+ /** Trading session. Default: `regular`. */
13
+ session?: TradingSession;
14
+ }
15
+ export interface QuoteSubscriptionEvents {
16
+ [event: string]: unknown[];
17
+ /** Initial values were received. */
18
+ loaded: [];
19
+ /** New values. `quote` is the merged snapshot, `changes` only the new fields. */
20
+ data: [quote: QuoteData, changes: QuoteData];
21
+ error: [error: TradingViewError];
22
+ }
23
+ export interface QuoteSessionEvents {
24
+ [event: string]: unknown[];
25
+ error: [error: TradingViewError];
26
+ }
27
+ /** Key identifying a symbol + session in quote packets. */
28
+ export declare function quoteSymbolKey(symbol: string, session?: TradingSession): string;
29
+ /** Live quotes for one symbol. Create it with `quoteSession.subscribe()`. */
30
+ export declare class QuoteSubscription extends Emitter<QuoteSubscriptionEvents> {
31
+ #private;
32
+ readonly symbol: string;
33
+ readonly session: TradingSession;
34
+ /** @internal */
35
+ readonly key: string;
36
+ /** @internal Use `quoteSession.subscribe()`. */
37
+ constructor(symbol: string, session: TradingSession, onClose: (subscription: QuoteSubscription) => void);
38
+ /** Latest merged values. */
39
+ get data(): QuoteData;
40
+ /** True after the initial values were received. */
41
+ get isLoaded(): boolean;
42
+ get isClosed(): boolean;
43
+ /** Stops receiving quotes for this subscription. Idempotent. */
44
+ close(): void;
45
+ /** @internal Copies the state of a loaded subscription to the same symbol. */
46
+ seed(source: QuoteSubscription): void;
47
+ /** @internal */
48
+ handlePacket(packet: ServerPacket): void;
49
+ /** @internal */
50
+ handleClose(error: TradingViewError, expected: boolean): void;
51
+ }
52
+ /**
53
+ * A set of live quote subscriptions sharing the same fields.
54
+ * Create it with `client.createQuoteSession()`.
55
+ */
56
+ export declare class QuoteSession extends Emitter<QuoteSessionEvents> {
57
+ #private;
58
+ readonly id: string;
59
+ readonly client: TradingViewClient;
60
+ constructor(client: TradingViewClient, options?: QuoteSessionOptions);
61
+ /** Requested fields. */
62
+ get fields(): readonly QuoteField[];
63
+ get isDeleted(): boolean;
64
+ /** Changes the requested fields for every subscription. */
65
+ setFields(fields: QuoteFieldPreset | readonly QuoteField[]): void;
66
+ /**
67
+ * Subscribes to a symbol. Several subscriptions to the same symbol share
68
+ * one server subscription.
69
+ */
70
+ subscribe(symbol: string, options?: QuoteSubscriptionOptions): QuoteSubscription;
71
+ /** Deletes the session and all its subscriptions. Idempotent. */
72
+ delete(): void;
73
+ }
@@ -0,0 +1,205 @@
1
+ import { TradingViewError } from '../errors.js';
2
+ import { Emitter } from '../events.js';
3
+ import { createSessionId } from '../protocol/ids.js';
4
+ import { resolveQuoteFields, } from './fields.js';
5
+ /** Key identifying a symbol + session in quote packets. */
6
+ export function quoteSymbolKey(symbol, session = 'regular') {
7
+ return `=${JSON.stringify({ session, symbol })}`;
8
+ }
9
+ /** Live quotes for one symbol. Create it with `quoteSession.subscribe()`. */
10
+ export class QuoteSubscription extends Emitter {
11
+ symbol;
12
+ session;
13
+ /** @internal */
14
+ key;
15
+ #onClose;
16
+ #data = {};
17
+ #loaded = false;
18
+ #closed = false;
19
+ /** @internal Use `quoteSession.subscribe()`. */
20
+ constructor(symbol, session, onClose) {
21
+ super();
22
+ this.symbol = symbol;
23
+ this.session = session;
24
+ this.key = quoteSymbolKey(symbol, session);
25
+ this.#onClose = onClose;
26
+ }
27
+ /** Latest merged values. */
28
+ get data() {
29
+ return { ...this.#data };
30
+ }
31
+ /** True after the initial values were received. */
32
+ get isLoaded() {
33
+ return this.#loaded;
34
+ }
35
+ get isClosed() {
36
+ return this.#closed;
37
+ }
38
+ /** Stops receiving quotes for this subscription. Idempotent. */
39
+ close() {
40
+ if (this.#closed)
41
+ return;
42
+ this.#closed = true;
43
+ this.#onClose(this);
44
+ }
45
+ /** @internal Copies the state of a loaded subscription to the same symbol. */
46
+ seed(source) {
47
+ if (!source.isLoaded)
48
+ return;
49
+ queueMicrotask(() => {
50
+ if (this.#closed || this.#loaded)
51
+ return;
52
+ this.#data = source.data;
53
+ this.#loaded = true;
54
+ this.emit('data', this.data, this.data);
55
+ this.emit('loaded');
56
+ });
57
+ }
58
+ /** @internal */
59
+ handlePacket(packet) {
60
+ if (this.#closed)
61
+ return;
62
+ if (packet.m === 'quote_completed') {
63
+ this.#loaded = true;
64
+ this.emit('loaded');
65
+ return;
66
+ }
67
+ const payload = packet.p[1];
68
+ if (payload?.s === 'ok') {
69
+ const changes = { ...payload.v };
70
+ this.#data = { ...this.#data, ...changes };
71
+ this.emit('data', this.data, changes);
72
+ }
73
+ else if (payload?.s === 'error') {
74
+ this.emit('error', new TradingViewError('QUOTE_ERROR', `Quote error (${this.symbol}): ${payload.errmsg ?? 'unknown'}`, {
75
+ details: packet.p,
76
+ }));
77
+ }
78
+ }
79
+ /** @internal */
80
+ handleClose(error, expected) {
81
+ if (this.#closed)
82
+ return;
83
+ this.#closed = true;
84
+ if (!expected)
85
+ this.emit('error', error);
86
+ }
87
+ }
88
+ /**
89
+ * A set of live quote subscriptions sharing the same fields.
90
+ * Create it with `client.createQuoteSession()`.
91
+ */
92
+ export class QuoteSession extends Emitter {
93
+ id = createSessionId('qs');
94
+ client;
95
+ #subscriptions = new Map();
96
+ #fields;
97
+ #deleted = false;
98
+ constructor(client, options = {}) {
99
+ super();
100
+ this.client = client;
101
+ this.#fields = resolveQuoteFields(options.fields);
102
+ client.registerSession(this.id, {
103
+ onPacket: (packet) => this.#onPacket(packet),
104
+ onClose: (error, expected) => this.#onClientClose(error, expected),
105
+ });
106
+ client.send('quote_create_session', [this.id]);
107
+ client.send('quote_set_fields', [this.id, ...this.#fields]);
108
+ }
109
+ /** Requested fields. */
110
+ get fields() {
111
+ return this.#fields;
112
+ }
113
+ get isDeleted() {
114
+ return this.#deleted;
115
+ }
116
+ /** Changes the requested fields for every subscription. */
117
+ setFields(fields) {
118
+ this.#assertAlive();
119
+ this.#fields = resolveQuoteFields(fields);
120
+ this.client.send('quote_set_fields', [this.id, ...this.#fields]);
121
+ }
122
+ /**
123
+ * Subscribes to a symbol. Several subscriptions to the same symbol share
124
+ * one server subscription.
125
+ */
126
+ subscribe(symbol, options = {}) {
127
+ this.#assertAlive();
128
+ if (!symbol)
129
+ throw new TradingViewError('INVALID_ARGUMENT', 'A symbol is required');
130
+ const subscription = new QuoteSubscription(symbol, options.session ?? 'regular', (sub) => this.#release(sub));
131
+ let set = this.#subscriptions.get(subscription.key);
132
+ if (!set) {
133
+ set = new Set();
134
+ this.#subscriptions.set(subscription.key, set);
135
+ this.client.send('quote_add_symbols', [this.id, subscription.key]);
136
+ }
137
+ else {
138
+ const loaded = [...set].find((sub) => sub.isLoaded);
139
+ if (loaded)
140
+ subscription.seed(loaded);
141
+ }
142
+ set.add(subscription);
143
+ return subscription;
144
+ }
145
+ /** Deletes the session and all its subscriptions. Idempotent. */
146
+ delete() {
147
+ if (this.#deleted)
148
+ return;
149
+ this.#deleted = true;
150
+ if (!this.client.isClosed)
151
+ this.client.send('quote_delete_session', [this.id]);
152
+ this.client.unregisterSession(this.id);
153
+ for (const set of this.#subscriptions.values())
154
+ for (const sub of set)
155
+ sub.close();
156
+ this.#subscriptions.clear();
157
+ }
158
+ #release(subscription) {
159
+ const set = this.#subscriptions.get(subscription.key);
160
+ if (!set?.delete(subscription))
161
+ return;
162
+ if (set.size === 0) {
163
+ this.#subscriptions.delete(subscription.key);
164
+ if (!this.#deleted && !this.client.isClosed) {
165
+ this.client.send('quote_remove_symbols', [this.id, subscription.key]);
166
+ }
167
+ }
168
+ }
169
+ #assertAlive() {
170
+ if (this.#deleted)
171
+ throw new TradingViewError('INVALID_STATE', 'The quote session is deleted');
172
+ }
173
+ #onClientClose(error, expected) {
174
+ if (this.#deleted)
175
+ return;
176
+ this.#deleted = true;
177
+ if (!expected)
178
+ this.emit('error', error);
179
+ for (const set of this.#subscriptions.values())
180
+ for (const sub of set)
181
+ sub.handleClose(error, expected);
182
+ this.#subscriptions.clear();
183
+ }
184
+ #onPacket(packet) {
185
+ this.client.log('quote', this.id, packet);
186
+ let key;
187
+ if (packet.m === 'quote_completed')
188
+ key = String(packet.p[1]);
189
+ else if (packet.m === 'qsd')
190
+ key = packet.p[1]?.n;
191
+ else
192
+ return;
193
+ if (key === undefined)
194
+ return;
195
+ const set = this.#subscriptions.get(key);
196
+ if (!set) {
197
+ // Data for a symbol nobody listens to anymore.
198
+ if (!this.#deleted && !this.client.isClosed)
199
+ this.client.send('quote_remove_symbols', [this.id, key]);
200
+ return;
201
+ }
202
+ for (const sub of [...set])
203
+ sub.handlePacket(packet);
204
+ }
205
+ }
@@ -0,0 +1,58 @@
1
+ # TradingView-API
2
+
3
+ **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.
4
+
5
+ <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>
6
+
7
+ **Idioma:** [English](../README.md) · [Français](README.fr.md) · Español · [Português](README.pt.md)
8
+
9
+ **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.
10
+
11
+ > **¿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.
12
+
13
+ > **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.
14
+
15
+ ## Elige cómo empezar
16
+
17
+ - **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).
18
+ - **Con Claude Code, Codex, OpenClaw u otro asistente:** comparte este repositorio y la [guía de la API de datos](data-api.md).
19
+ - **Sin instalación local:** [Molted](https://molted.cloud/) ofrece un espacio de trabajo con agente alojado que puede trabajar desde este repositorio. Es opcional.
20
+
21
+ ## API de datos
22
+
23
+ ```ts
24
+ import { getCandles, watchCandles, getQuote } from '@mathieuc/tradingview/data';
25
+
26
+ const candles = await getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: 'D', count: 100 });
27
+ console.log(candles.at(-1)); // { time, open, high, low, close, volume }, de la más antigua a la más reciente
28
+
29
+ const quote = await getQuote('BINANCE:BTCUSDT');
30
+
31
+ const watcher = await watchCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '1' }, {
32
+ onData: (snapshot) => console.log(snapshot.at(-1)?.close),
33
+ onError: console.error,
34
+ });
35
+ await watcher.stop();
36
+ ```
37
+
38
+ 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`. Detalles: [guía de la API de datos](data-api.md).
39
+
40
+ ## API de bajo nivel
41
+
42
+ ```ts
43
+ import { TradingViewClient } from '@mathieuc/tradingview';
44
+
45
+ const client = new TradingViewClient();
46
+ const chart = client.createChart();
47
+ chart.on('update', () => console.log(chart.lastCandle?.close));
48
+ chart.setMarket('BINANCE:BTCUSDT', { timeframe: 'D' });
49
+ // Al terminar: await client.close();
50
+ ```
51
+
52
+ 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).
53
+
54
+ 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.
55
+
56
+ [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)
57
+
58
+ 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.
@@ -0,0 +1,58 @@
1
+ # TradingView-API
2
+
3
+ **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.
4
+
5
+ <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>
6
+
7
+ **Langue :** [English](../README.md) · Français · [Español](README.es.md) · [Português](README.pt.md)
8
+
9
+ **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.
10
+
11
+ > **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.
12
+
13
+ > **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`.
14
+
15
+ ## Choisissez votre parcours
16
+
17
+ - **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).
18
+ - **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).
19
+ - **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.
20
+
21
+ ## API de données
22
+
23
+ ```ts
24
+ import { getCandles, watchCandles, getQuote } from '@mathieuc/tradingview/data';
25
+
26
+ const candles = await getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: 'D', count: 100 });
27
+ console.log(candles.at(-1)); // { time, open, high, low, close, volume }, du plus ancien au plus récent
28
+
29
+ const quote = await getQuote('BINANCE:BTCUSDT');
30
+
31
+ const watcher = await watchCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '1' }, {
32
+ onData: (snapshot) => console.log(snapshot.at(-1)?.close),
33
+ onError: console.error,
34
+ });
35
+ await watcher.stop();
36
+ ```
37
+
38
+ 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`. Détails : [guide de l'API de données](data-api.md).
39
+
40
+ ## API bas niveau
41
+
42
+ ```ts
43
+ import { TradingViewClient } from '@mathieuc/tradingview';
44
+
45
+ const client = new TradingViewClient();
46
+ const chart = client.createChart();
47
+ chart.on('update', () => console.log(chart.lastCandle?.close));
48
+ chart.setMarket('BINANCE:BTCUSDT', { timeframe: 'D' });
49
+ // À la fin : await client.close();
50
+ ```
51
+
52
+ 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).
53
+
54
+ 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.
55
+
56
+ [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)
57
+
58
+ 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.
@@ -0,0 +1,58 @@
1
+ # TradingView-API
2
+
3
+ **Experimente com um agente hospedado:** [Crie um monitor de mercado no Molted Studio](https://molted.studio/dreams/market-watch-alerts) — sem instalação local.
4
+
5
+ <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>
6
+
7
+ **Idioma:** [English](../README.md) · [Français](README.fr.md) · [Español](README.es.md) · Português
8
+
9
+ **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.
10
+
11
+ > **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.
12
+
13
+ > **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.
14
+
15
+ ## Escolha como começar
16
+
17
+ - **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).
18
+ - **Com Claude Code, Codex, OpenClaw ou outro assistente:** compartilhe este repositório e o [guia da API de dados](data-api.md).
19
+ - **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.
20
+
21
+ ## API de dados
22
+
23
+ ```ts
24
+ import { getCandles, watchCandles, getQuote } from '@mathieuc/tradingview/data';
25
+
26
+ const candles = await getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: 'D', count: 100 });
27
+ console.log(candles.at(-1)); // { time, open, high, low, close, volume }, do mais antigo ao mais recente
28
+
29
+ const quote = await getQuote('BINANCE:BTCUSDT');
30
+
31
+ const watcher = await watchCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '1' }, {
32
+ onData: (snapshot) => console.log(snapshot.at(-1)?.close),
33
+ onError: console.error,
34
+ });
35
+ await watcher.stop();
36
+ ```
37
+
38
+ 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`. Detalhes: [guia da API de dados](data-api.md).
39
+
40
+ ## API de baixo nível
41
+
42
+ ```ts
43
+ import { TradingViewClient } from '@mathieuc/tradingview';
44
+
45
+ const client = new TradingViewClient();
46
+ const chart = client.createChart();
47
+ chart.on('update', () => console.log(chart.lastCandle?.close));
48
+ chart.setMarket('BINANCE:BTCUSDT', { timeframe: 'D' });
49
+ // Ao terminar: await client.close();
50
+ ```
51
+
52
+ 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).
53
+
54
+ 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.
55
+
56
+ [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)
57
+
58
+ 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.