mtcli-volume 2.1.0__tar.gz → 2.2.0.dev1__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: mtcli-volume
3
- Version: 2.1.0
3
+ Version: 2.2.0.dev1
4
4
  Summary: Plugin mtcli para exibir o volume profile
5
5
  Author: Valmir França da Silva
6
6
  Author-email: vfranca3@gmail.com
@@ -0,0 +1,83 @@
1
+ from datetime import datetime, timedelta, timezone
2
+ import zoneinfo # Python 3.9+
3
+
4
+ import numpy as np
5
+
6
+ from mtcli.logger import setup_logger
7
+ from mtcli_volume.models.volume_model import (
8
+ calcular_estatisticas,
9
+ calcular_profile,
10
+ obter_rates,
11
+ )
12
+
13
+ log = setup_logger()
14
+
15
+
16
+ def calcular_volume_profile(
17
+ symbol,
18
+ period,
19
+ bars,
20
+ step,
21
+ volume,
22
+ data_inicio=None,
23
+ data_fim=None,
24
+ verbose=False,
25
+ timezone_str="America/Sao_Paulo",
26
+ ):
27
+ """Controla o fluxo de cálculo do volume profile, com suporte a timezone configurável."""
28
+ volume = volume.lower().strip()
29
+ if volume not in ["tick", "real"]:
30
+ log.error(f"Tipo de volume inválido: {volume}. Use 'tick' ou 'real'.")
31
+ raise ValueError(f"Tipo de volume inválido: {volume}. Use 'tick' ou 'real'.")
32
+
33
+ rates = obter_rates(symbol, period, bars, data_inicio, data_fim)
34
+
35
+ if rates is None or len(rates) == 0:
36
+ log.error("Falha ao obter dados de preços para cálculo do volume profile.")
37
+ return {}, {}, {}
38
+
39
+ profile = calcular_profile(rates, step, volume)
40
+ stats = calcular_estatisticas(profile)
41
+
42
+ # Captura de informações de contexto
43
+ info = {}
44
+ if isinstance(rates, np.ndarray) and len(rates) > 0:
45
+ primeiro = rates[0]
46
+ ultimo = rates[-1]
47
+ if "time" in rates.dtype.names:
48
+ try:
49
+ # Define fuso horário desejado
50
+ try:
51
+ fuso = zoneinfo.ZoneInfo(timezone_str)
52
+ except Exception:
53
+ log.warning(
54
+ f"Fuso horário '{timezone_str}' inválido. Usando UTC−3 (Brasília)."
55
+ )
56
+ fuso = timezone(timedelta(hours=-3))
57
+
58
+ inicio_real = (
59
+ datetime.utcfromtimestamp(float(primeiro["time"]))
60
+ .astimezone(fuso)
61
+ .strftime("%Y-%m-%d %H:%M:%S")
62
+ )
63
+ fim_real = (
64
+ datetime.utcfromtimestamp(float(ultimo["time"]))
65
+ .astimezone(fuso)
66
+ .strftime("%Y-%m-%d %H:%M:%S")
67
+ )
68
+ except Exception as e:
69
+ log.error(f"Erro ao converter timezone: {e}")
70
+ inicio_real = fim_real = "?"
71
+ else:
72
+ inicio_real = fim_real = "?"
73
+
74
+ info = {
75
+ "symbol": symbol,
76
+ "period": period,
77
+ "candles": len(rates),
78
+ "inicio": inicio_real,
79
+ "fim": fim_real,
80
+ "timezone": timezone_str,
81
+ }
82
+
83
+ return profile, stats, info
@@ -0,0 +1,129 @@
1
+ from collections import defaultdict
2
+ from collections.abc import Mapping
3
+ from datetime import datetime
4
+
5
+ import MetaTrader5 as mt5
6
+ import numpy as np
7
+
8
+ from mtcli.logger import setup_logger
9
+ from mtcli.mt5_context import mt5_conexao
10
+ from mtcli_volume.conf import DIGITOS
11
+
12
+ log = setup_logger()
13
+
14
+
15
+ def obter_rates(
16
+ symbol: str,
17
+ period: str,
18
+ bars: int,
19
+ data_inicio: datetime = None,
20
+ data_fim: datetime = None,
21
+ ):
22
+ """Obtém dados históricos via MetaTrader 5, podendo filtrar por intervalo de tempo."""
23
+ with mt5_conexao():
24
+ tf = getattr(mt5, f"TIMEFRAME_{period.upper()}", None)
25
+ if tf is None:
26
+ log.error(f"Timeframe inválido: {period}")
27
+ return None
28
+
29
+ if not mt5.symbol_select(symbol, True):
30
+ log.error(f"Erro ao selecionar símbolo {symbol}")
31
+ return None
32
+
33
+ try:
34
+ if data_inicio and data_fim:
35
+ log.debug(
36
+ f"Obtendo candles de {symbol} entre {data_inicio} e {data_fim}"
37
+ )
38
+ rates = mt5.copy_rates_range(symbol, tf, data_inicio, data_fim)
39
+ else:
40
+ log.debug(f"Obtendo {bars} candles de {symbol} a partir da posição 0")
41
+ rates = mt5.copy_rates_from_pos(symbol, tf, 0, bars)
42
+ except Exception as e:
43
+ log.error(f"Erro ao obter dados históricos: {e}")
44
+ return None
45
+
46
+ # ✅ Correção para arrays NumPy
47
+ if rates is None or len(rates) == 0:
48
+ log.error("Nenhum dado retornado.")
49
+ return None
50
+
51
+ return rates
52
+
53
+
54
+ def calcular_profile(
55
+ rates: list[dict | tuple | object],
56
+ step: float,
57
+ volume: str = "tick",
58
+ ) -> dict[float, float]:
59
+ """Calcula o volume total por faixa de preço, suportando dicionários, numpy.void, objetos ou tuplas."""
60
+ profile = defaultdict(int)
61
+
62
+ for r in rates:
63
+ # --- 1️⃣ Dict comum ---
64
+ if isinstance(r, Mapping):
65
+ preco = r["close"]
66
+ tick_volume = r["tick_volume"]
67
+ real_volume = r.get("real_volume", tick_volume)
68
+
69
+ # --- 2️⃣ numpy.void (estrutura MT5) ---
70
+ elif isinstance(r, np.void):
71
+ preco = float(r["close"])
72
+ tick_volume = int(r["tick_volume"])
73
+ # real_volume pode não existir dependendo da corretora
74
+ real_volume = (
75
+ int(r["real_volume"]) if "real_volume" in r.dtype.names else tick_volume
76
+ )
77
+
78
+ # --- 3️⃣ Objeto com atributos (ex: namedtuple) ---
79
+ elif hasattr(r, "close"):
80
+ preco = r.close
81
+ tick_volume = r.tick_volume
82
+ real_volume = getattr(r, "real_volume", tick_volume)
83
+
84
+ # --- 4️⃣ Tupla/lista ---
85
+ elif isinstance(r, (tuple, list)) and len(r) >= 6:
86
+ preco = r[4]
87
+ tick_volume = r[5]
88
+ real_volume = r[6] if len(r) > 6 else tick_volume
89
+
90
+ else:
91
+ raise TypeError(f"Formato de rate desconhecido: {type(r)}")
92
+
93
+ faixa = round(round(preco / step) * step, DIGITOS)
94
+ profile[faixa] += tick_volume if volume == "tick" else real_volume
95
+
96
+ return dict(profile)
97
+
98
+
99
+ def calcular_estatisticas(profile):
100
+ """Calcula POC, área de valor (70%), HVNs e LVNs."""
101
+ if not profile:
102
+ return {"poc": None, "area_valor": (None, None), "hvns": [], "lvns": []}
103
+
104
+ # Ordena as faixas de preço por volume (desc)
105
+ volumes_ordenados = sorted(profile.items(), key=lambda x: x[1], reverse=True)
106
+ poc = volumes_ordenados[0][0]
107
+
108
+ # Cálculo da área de valor (70%)
109
+ total_volume = sum(profile.values())
110
+ acumulado = 0
111
+ faixas_area_valor = []
112
+ for faixa, vol in volumes_ordenados:
113
+ acumulado += vol
114
+ faixas_area_valor.append(faixa)
115
+ if acumulado >= total_volume * 0.7:
116
+ break
117
+ area_valor = (min(faixas_area_valor), max(faixas_area_valor))
118
+
119
+ # HVNs e LVNs
120
+ media = total_volume / len(profile)
121
+ hvns = sorted([faixa for faixa, vol in profile.items() if vol >= media * 1.5])
122
+ lvns = sorted([faixa for faixa, vol in profile.items() if vol <= media * 0.5])
123
+
124
+ return {
125
+ "poc": poc,
126
+ "area_valor": area_valor,
127
+ "hvns": hvns,
128
+ "lvns": lvns,
129
+ }
@@ -1,5 +1,5 @@
1
- from mtcli_volume.commands.volume_cli import volume
2
-
3
-
4
- def register(cli):
5
- cli.add_command(volume, name="volume")
1
+ from mtcli_volume.volume import volume
2
+
3
+
4
+ def register(cli):
5
+ cli.add_command(volume, name="volume")
@@ -0,0 +1,69 @@
1
+ import click
2
+
3
+ from mtcli_volume.conf import DIGITOS
4
+
5
+ BARRA_CHAR = "#"
6
+
7
+
8
+ def exibir_volume_profile(profile, stats, symbol, info=None, verbose=False):
9
+ """Exibe o volume profile no terminal de forma acessível e organizada."""
10
+ if not profile:
11
+ click.echo(f"Nenhum dado disponível para {symbol}")
12
+ return
13
+
14
+ # ──────────────────────────────────────────────
15
+ # BLOCO VERBOSO: exibe detalhes da análise
16
+ # ──────────────────────────────────────────────
17
+ if verbose and info:
18
+ click.echo("\n=== Informações da Análise ===")
19
+ linhas = [
20
+ ("Símbolo", info.get("symbol", "?")),
21
+ ("Timeframe", info.get("period", "?").upper()),
22
+ ("Candles analisados", str(info.get("candles", "?"))),
23
+ (
24
+ "Período analisado",
25
+ f"{info.get('inicio', '?')} → {info.get('fim', '?')}",
26
+ ),
27
+ ("Fuso horário", info.get("timezone", "Desconhecido")),
28
+ ]
29
+ largura_esq = max(len(t[0]) for t in linhas) + 2
30
+ for chave, valor in linhas:
31
+ click.echo(f"{chave:<{largura_esq}}: {valor}")
32
+ click.echo("=" * (largura_esq + 30))
33
+
34
+ # ──────────────────────────────────────────────
35
+ # BLOCO PRINCIPAL: Volume Profile
36
+ # ──────────────────────────────────────────────
37
+ dados_ordenados = sorted(profile.items(), reverse=True)
38
+ click.echo(f"\n📊 Volume Profile — {symbol}\n")
39
+
40
+ max_vol = max(profile.values())
41
+ largura_preco = max(len(f"{p:.{DIGITOS}f}") for p in profile.keys())
42
+
43
+ # Cabeçalho
44
+ click.echo(f"{'Preço':>{largura_preco}} | Volume | Distribuição")
45
+ click.echo("-" * (largura_preco + 32))
46
+
47
+ # Corpo da tabela
48
+ for preco, vol in dados_ordenados:
49
+ barra_len = int(vol / max_vol * 50)
50
+ barra = BARRA_CHAR * barra_len
51
+ click.echo(f"{preco:>{largura_preco}.{DIGITOS}f} | {vol:>6} | {barra}")
52
+
53
+ # ──────────────────────────────────────────────
54
+ # BLOCO FINAL: Estatísticas
55
+ # ──────────────────────────────────────────────
56
+ click.echo("\n=== Estatísticas ===")
57
+ if stats.get("poc") is not None:
58
+ click.echo(f"POC : {stats['poc']:.{DIGITOS}f}")
59
+ click.echo(
60
+ f"Área de Valor : {stats['area_valor'][0]:.{DIGITOS}f} → {stats['area_valor'][1]:.{DIGITOS}f}"
61
+ )
62
+ click.echo(
63
+ f"HVNs (High Vol.) : {', '.join(map(lambda x: f'{x:.{DIGITOS}f}', stats['hvns'])) or 'Nenhum'}"
64
+ )
65
+ click.echo(
66
+ f"LVNs (Low Vol.) : {', '.join(map(lambda x: f'{x:.{DIGITOS}f}', stats['lvns'])) or 'Nenhum'}"
67
+ )
68
+ else:
69
+ click.echo("Estatísticas indisponíveis (dados insuficientes).")
@@ -0,0 +1,69 @@
1
+ from datetime import datetime
2
+
3
+ import click
4
+
5
+ from mtcli_volume.conf import BARS, PERIOD, STEP, SYMBOL, VOLUME
6
+ from mtcli_volume.controllers.volume_controller import calcular_volume_profile
7
+ from mtcli_volume.views.volume_view import exibir_volume_profile
8
+
9
+
10
+ @click.command(
11
+ "volume",
12
+ help="Exibe o Volume Profile, agrupando volumes por faixa de preço no histórico recente.",
13
+ )
14
+ @click.version_option(package_name="mtcli-volume")
15
+ @click.option(
16
+ "--symbol", "-s", default=SYMBOL, show_default=True, help="Símbolo do ativo."
17
+ )
18
+ @click.option(
19
+ "--period",
20
+ "-p",
21
+ default=PERIOD,
22
+ show_default=True,
23
+ help="Timeframe (ex: M1, M5, H1).",
24
+ )
25
+ @click.option("--bars", "-b", default=BARS, show_default=True, help="Número de barras.")
26
+ @click.option(
27
+ "--step",
28
+ "-e",
29
+ type=float,
30
+ default=STEP,
31
+ show_default=True,
32
+ help="Tamanho do agrupamento de preços.",
33
+ )
34
+ @click.option(
35
+ "--volume",
36
+ "-v",
37
+ default=VOLUME,
38
+ show_default=True,
39
+ help="Tipo de volume (tick ou real).",
40
+ )
41
+ @click.option(
42
+ "--from", "data_inicio", type=str, help="Data/hora inicial (YYYY-MM-DD HH:MM)."
43
+ )
44
+ @click.option("--to", "data_fim", type=str, help="Data/hora final (YYYY-MM-DD HH:MM).")
45
+ @click.option(
46
+ "--verbose",
47
+ "-vv",
48
+ is_flag=True,
49
+ help="Mostra informações detalhadas sobre a análise.",
50
+ )
51
+ @click.option(
52
+ "--timezone",
53
+ "-tz",
54
+ type=str,
55
+ default="America/Sao_Paulo",
56
+ show_default=True,
57
+ help="Fuso horário para exibição das datas (ex: 'UTC', 'America/Sao_Paulo').",
58
+ )
59
+ def volume(
60
+ symbol, period, bars, step, volume, data_inicio, data_fim, verbose, timezone
61
+ ):
62
+ """Exibe o Volume Profile agrupando volumes por faixa de preço."""
63
+ inicio = datetime.strptime(data_inicio, "%Y-%m-%d %H:%M") if data_inicio else None
64
+ fim = datetime.strptime(data_fim, "%Y-%m-%d %H:%M") if data_fim else None
65
+
66
+ profile, stats, info = calcular_volume_profile(
67
+ symbol, period, bars, step, volume, inicio, fim, verbose, timezone
68
+ )
69
+ exibir_volume_profile(profile, stats, symbol, info, verbose)
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mtcli-volume"
3
- version = "2.1.0"
3
+ version = "2.2.0.dev1"
4
4
  description = "Plugin mtcli para exibir o volume profile"
5
5
  authors = [
6
6
  {name = "Valmir França da Silva",email = "vfranca3@gmail.com"}
@@ -1,46 +0,0 @@
1
- import click
2
-
3
- from mtcli_volume.conf import BARS, PERIOD, STEP, SYMBOL, VOLUME
4
- from mtcli_volume.controllers.volume_controller import calcular_volume_profile
5
- from mtcli_volume.views.volume_view import exibir_volume_profile
6
-
7
-
8
- @click.command(
9
- "volume",
10
- help="Exibe o Volume Profile, agrupando volumes por faixa de preço no histórico recente.",
11
- )
12
- @click.version_option(package_name="mtcli-volume")
13
- @click.option(
14
- "--symbol", "-s", default=SYMBOL, show_default=True, help="Simbolo do ativo."
15
- )
16
- @click.option(
17
- "--period",
18
- "-p",
19
- default=PERIOD,
20
- show_default=True,
21
- help="Timeframe (ex: M1, M5, H1).",
22
- )
23
- @click.option("--bars", "-b", default=BARS, show_default=True, help="Numero de barras.")
24
- @click.option(
25
- "--step",
26
- "-e",
27
- type=float,
28
- default=STEP,
29
- show_default=True,
30
- help="Tamanho do agrupamento de precos.",
31
- )
32
- @click.option(
33
- "--volume",
34
- "-v",
35
- default=VOLUME,
36
- show_default=True,
37
- help="Tipo de volume (tick ou real).",
38
- )
39
- def volume(symbol, period, bars, step, volume):
40
- """Exibe o Volume Profile agrupando volumes por faixa de preço."""
41
- profile, stats = calcular_volume_profile(symbol, period, bars, step, volume)
42
- exibir_volume_profile(profile, stats, symbol)
43
-
44
-
45
- if __name__ == "__main__":
46
- volume()
@@ -1,26 +0,0 @@
1
- from mtcli.logger import setup_logger
2
- from mtcli_volume.models.volume_model import (
3
- calcular_estatisticas,
4
- calcular_profile,
5
- obter_rates,
6
- )
7
-
8
- log = setup_logger()
9
-
10
-
11
- def calcular_volume_profile(symbol, period, bars, step, volume):
12
- """Controla o fluxo de cálculo do volume profile."""
13
- volume = volume.lower().strip()
14
- if volume not in ["tick", "real"]:
15
- log.error(f"Tipo de volume inválido: {volume}. Use 'tick' ou 'real'.")
16
- raise ValueError(f"Tipo de volume inválido: {volume}. Use 'tick' ou 'real'.")
17
-
18
- rates = obter_rates(symbol, period, bars)
19
- if not rates:
20
- log.error("Falha ao obter dados de preços para cálculo do volume profile.")
21
- return {}, {}
22
-
23
- profile = calcular_profile(rates, step, volume)
24
- stats = calcular_estatisticas(profile)
25
-
26
- return profile, stats
@@ -1,98 +0,0 @@
1
- from collections import defaultdict
2
-
3
- import MetaTrader5 as mt5
4
-
5
- from mtcli.logger import setup_logger
6
- from mtcli.models.rates_model import RatesModel
7
- from mtcli.mt5_context import mt5_conexao
8
- from mtcli_volume.conf import DIGITOS
9
-
10
- log = setup_logger()
11
-
12
-
13
- def obter_rates(symbol, period, bars):
14
- """Obtém os dados históricos de preços via MetaTrader 5."""
15
- with mt5_conexao():
16
- tf = getattr(mt5, f"TIMEFRAME_{period.upper()}", None)
17
- if tf is None:
18
- log.error(f"Timeframe inválido: {period}")
19
- return
20
-
21
- if not mt5.symbol_select(symbol, True):
22
- log.error(f"Erro ao selecionar símbolo {symbol}")
23
- return
24
-
25
- rates = RatesModel(symbol, period, bars).get_data()
26
-
27
- if not rates:
28
- log.error("Erro: não foi possível obter os dados históricos.")
29
- return
30
-
31
- return rates
32
-
33
-
34
- def calcular_profile(rates, step, volume="tick"):
35
- """Calcula o volume total por faixa de preço, suportando dicionários, objetos ou tuplas."""
36
- from collections.abc import Mapping
37
-
38
- profile = defaultdict(int)
39
-
40
- for r in rates:
41
- # Detecta se r é dict, objeto com atributos ou tupla
42
- if isinstance(r, Mapping): # dict
43
- preco = r["close"]
44
- tick_volume = r["tick_volume"]
45
- real_volume = r.get("real_volume", tick_volume)
46
- elif hasattr(r, "close"): # objeto com atributos
47
- preco = r.close
48
- tick_volume = r.tick_volume
49
- real_volume = getattr(r, "real_volume", tick_volume)
50
- elif isinstance(r, (tuple, list)) and len(r) >= 6: # tupla com campos esperados
51
- preco = r[4] # índice típico de 'close' em rates do MT5
52
- tick_volume = r[5]
53
- real_volume = r[6] if len(r) > 6 else tick_volume
54
- else:
55
- raise TypeError(f"Formato de rate desconhecido: {type(r)}")
56
-
57
- faixa = round(round(preco / step) * step, DIGITOS)
58
- profile[faixa] += tick_volume if volume == "tick" else real_volume
59
-
60
- return dict(profile)
61
-
62
-
63
- def calcular_estatisticas(profile):
64
- """Calcula POC, área de valor (70%), HVNs e LVNs."""
65
- if profile is None or len(profile) == 0:
66
- return {
67
- "poc": None,
68
- "area_valor": (None, None),
69
- "hvns": [],
70
- "lvns": [],
71
- }
72
-
73
- # Ordena faixas de preço pelo volume em ordem decrescente
74
- volumes_ordenados = sorted(profile.items(), key=lambda x: x[1], reverse=True)
75
- poc = volumes_ordenados[0][0]
76
-
77
- # Área de valor (70% do volume)
78
- total_volume = sum(profile.values())
79
- acumulado = 0
80
- faixas_area_valor = []
81
- for faixa, vol in volumes_ordenados:
82
- acumulado += vol
83
- faixas_area_valor.append(faixa)
84
- if acumulado >= total_volume * 0.7:
85
- break
86
- area_valor = (min(faixas_area_valor), max(faixas_area_valor))
87
-
88
- # HVNs (High Volume Nodes) e LVNs (Low Volume Nodes)
89
- media = total_volume / len(profile)
90
- hvns = sorted([faixa for faixa, vol in profile.items() if vol >= media * 1.5])
91
- lvns = sorted([faixa for faixa, vol in profile.items() if vol <= media * 0.5])
92
-
93
- return {
94
- "poc": poc,
95
- "area_valor": area_valor,
96
- "hvns": hvns,
97
- "lvns": lvns,
98
- }
@@ -1,29 +0,0 @@
1
- import click
2
-
3
- from mtcli_volume.conf import DIGITOS
4
-
5
- BARRA_CHAR = "#" # Pode mudar para "■" ou "=" se UTF-8 for garantido
6
-
7
-
8
- def exibir_volume_profile(profile, stats, symbol):
9
- """Exibe o volume profile no terminal."""
10
- if not profile:
11
- click.echo(f"Nenhum dado disponível para {symbol}")
12
- return
13
-
14
- dados_ordenados = sorted(profile.items(), reverse=True)
15
-
16
- click.echo(f"\nVolume Profile {symbol}\n")
17
- max_vol = max(profile.values())
18
- for preco, vol in dados_ordenados:
19
- barra = BARRA_CHAR * (vol // max(1, max_vol // 50))
20
- click.echo(f"{preco:>8.{DIGITOS}f} {vol:>6} {barra}")
21
-
22
- # Estatísticas
23
- if stats.get("poc") is not None:
24
- click.echo(f"\nPOC {stats['poc']:.{DIGITOS}f}")
25
- click.echo(f"VA {stats['area_valor'][0]:.{DIGITOS}f} a {stats['area_valor'][1]:.{DIGITOS}f}")
26
- click.echo(f"HVNs {stats['hvns']}")
27
- click.echo(f"LVNs {stats['lvns']}")
28
- else:
29
- click.echo("\nEstatísticas indisponíveis (dados insuficientes).")
File without changes