mtcli-risco 2.5.0__tar.gz → 2.5.1__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.
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/PKG-INFO +1 -1
- mtcli_risco-2.5.1/mtcli_risco/cli.py +33 -0
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/commands/checar.py +75 -75
- mtcli_risco-2.5.0/mtcli_risco/commands/trades.py → mtcli_risco-2.5.1/mtcli_risco/commands/lucro.py +51 -51
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/commands/monitorar.py +2 -2
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/commands/panic.py +2 -2
- mtcli_risco-2.5.1/mtcli_risco/commands/start.py +101 -0
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/commands/status.py +2 -2
- mtcli_risco-2.5.1/mtcli_risco/commands/stop.py +87 -0
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/conf.py +31 -31
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/models/checar_model.py +117 -117
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/models/hardstop_model.py +120 -120
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/models/panic_model.py +217 -217
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/models/trades_model.py +62 -62
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/services/monitor_service.py +7 -34
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/services/run_monitor.py +4 -11
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/pyproject.toml +1 -1
- mtcli_risco-2.5.0/mtcli_risco/cli.py +0 -33
- mtcli_risco-2.5.0/mtcli_risco/commands/start.py +0 -78
- mtcli_risco-2.5.0/mtcli_risco/commands/stop.py +0 -29
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/LICENSE +0 -0
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/README.md +0 -0
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/__init__.py +0 -0
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/commands/__init__.py +0 -0
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/models/__init__.py +0 -0
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/plugin.py +0 -0
- {mtcli_risco-2.5.0 → mtcli_risco-2.5.1}/mtcli_risco/services/__init__.py +0 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Comando principal e registro dos subcomandos
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
from .commands.checar import checar
|
|
7
|
+
from .commands.monitorar import monitorar
|
|
8
|
+
from .commands.lucro import lucro
|
|
9
|
+
from .commands.panic import panic
|
|
10
|
+
from .commands.start import start
|
|
11
|
+
from .commands.stop import stop
|
|
12
|
+
from .commands.status import status
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@click.group()
|
|
16
|
+
@click.version_option(package_name="mtcli-risco")
|
|
17
|
+
def cli():
|
|
18
|
+
"""
|
|
19
|
+
Plugin mtcli-risco.
|
|
20
|
+
|
|
21
|
+
Conjunto de comandos para gerenciamento e controle de risco diário
|
|
22
|
+
baseado em lucro/prejuízo no MetaTrader 5.
|
|
23
|
+
"""
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
cli.add_command(checar, name="checar")
|
|
28
|
+
cli.add_command(monitorar, name="monitorar")
|
|
29
|
+
cli.add_command(lucro, name="lucro")
|
|
30
|
+
cli.add_command(panic, name="panic")
|
|
31
|
+
cli.add_command(start, name="start")
|
|
32
|
+
cli.add_command(stop, name="stop")
|
|
33
|
+
cli.add_command(status, name="status")
|
|
@@ -1,75 +1,75 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Comando checar.
|
|
3
|
-
|
|
4
|
-
Verifica se o limite diário de prejuízo foi atingido e,
|
|
5
|
-
se necessário, encerra posições e bloqueia novas ordens.
|
|
6
|
-
"""
|
|
7
|
-
|
|
8
|
-
import click
|
|
9
|
-
from datetime import date
|
|
10
|
-
from mtcli.logger import setup_logger
|
|
11
|
-
from mtcli_risco.conf import LOSS_LIMIT, STATUS_FILE
|
|
12
|
-
from mtcli_risco.models.trades_model import calcular_lucro_total_dia
|
|
13
|
-
from mtcli_risco.models.checar_model import (
|
|
14
|
-
carregar_estado,
|
|
15
|
-
salvar_estado,
|
|
16
|
-
risco_excedido,
|
|
17
|
-
encerrar_todas_posicoes,
|
|
18
|
-
cancelar_todas_ordens,
|
|
19
|
-
)
|
|
20
|
-
|
|
21
|
-
log = setup_logger()
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
@click.command(
|
|
25
|
-
"checar",
|
|
26
|
-
help="Verifica se o limite diário de prejuízo foi atingido.",
|
|
27
|
-
)
|
|
28
|
-
@click.version_option(package_name="mtcli-risco")
|
|
29
|
-
@click.option(
|
|
30
|
-
"--limite",
|
|
31
|
-
"-l",
|
|
32
|
-
default=LOSS_LIMIT,
|
|
33
|
-
help="Limite de perda diária (ex: -500).",
|
|
34
|
-
)
|
|
35
|
-
@click.option(
|
|
36
|
-
"--lucro",
|
|
37
|
-
is_flag=True,
|
|
38
|
-
default=False,
|
|
39
|
-
help="Exibe o lucro total do dia e encerra.",
|
|
40
|
-
)
|
|
41
|
-
def
|
|
42
|
-
"""
|
|
43
|
-
Executa uma verificação pontual do risco diário.
|
|
44
|
-
"""
|
|
45
|
-
if lucro:
|
|
46
|
-
total = calcular_lucro_total_dia()
|
|
47
|
-
click.echo(f"Lucro total do dia: {total:.2f}")
|
|
48
|
-
log.info(f"[RISCO] Lucro total do dia: {total:.2f}")
|
|
49
|
-
return
|
|
50
|
-
|
|
51
|
-
hoje = date.today()
|
|
52
|
-
estado = carregar_estado(STATUS_FILE)
|
|
53
|
-
|
|
54
|
-
# Reset diário
|
|
55
|
-
if estado["data"] != hoje.isoformat():
|
|
56
|
-
log.info("[ESTADO] Novo dia detectado, resetando bloqueio.")
|
|
57
|
-
estado["bloqueado"] = False
|
|
58
|
-
salvar_estado(STATUS_FILE, hoje, False)
|
|
59
|
-
|
|
60
|
-
if estado["bloqueado"]:
|
|
61
|
-
click.echo("Sistema bloqueado hoje por limite de risco.")
|
|
62
|
-
log.warning("[RISCO] Sistema já bloqueado hoje.")
|
|
63
|
-
return
|
|
64
|
-
|
|
65
|
-
if risco_excedido(limite):
|
|
66
|
-
click.echo(
|
|
67
|
-
f"Limite {limite:.2f} excedido. Encerrando posições e bloqueando ordens."
|
|
68
|
-
)
|
|
69
|
-
log.warning(f"[RISCO] Limite {limite:.2f} excedido.")
|
|
70
|
-
encerrar_todas_posicoes()
|
|
71
|
-
cancelar_todas_ordens()
|
|
72
|
-
salvar_estado(STATUS_FILE, hoje, True)
|
|
73
|
-
else:
|
|
74
|
-
click.echo("Dentro do limite de risco.")
|
|
75
|
-
log.info(f"[RISCO] Dentro do limite {limite:.2f}.")
|
|
1
|
+
"""
|
|
2
|
+
Comando checar.
|
|
3
|
+
|
|
4
|
+
Verifica se o limite diário de prejuízo foi atingido e,
|
|
5
|
+
se necessário, encerra posições e bloqueia novas ordens.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import click
|
|
9
|
+
from datetime import date
|
|
10
|
+
from mtcli.logger import setup_logger
|
|
11
|
+
from mtcli_risco.conf import LOSS_LIMIT, STATUS_FILE
|
|
12
|
+
from mtcli_risco.models.trades_model import calcular_lucro_total_dia
|
|
13
|
+
from mtcli_risco.models.checar_model import (
|
|
14
|
+
carregar_estado,
|
|
15
|
+
salvar_estado,
|
|
16
|
+
risco_excedido,
|
|
17
|
+
encerrar_todas_posicoes,
|
|
18
|
+
cancelar_todas_ordens,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
log = setup_logger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@click.command(
|
|
25
|
+
"checar",
|
|
26
|
+
help="Verifica se o limite diário de prejuízo foi atingido.",
|
|
27
|
+
)
|
|
28
|
+
@click.version_option(package_name="mtcli-risco")
|
|
29
|
+
@click.option(
|
|
30
|
+
"--limite",
|
|
31
|
+
"-l",
|
|
32
|
+
default=LOSS_LIMIT,
|
|
33
|
+
help="Limite de perda diária (ex: -500).",
|
|
34
|
+
)
|
|
35
|
+
@click.option(
|
|
36
|
+
"--lucro",
|
|
37
|
+
is_flag=True,
|
|
38
|
+
default=False,
|
|
39
|
+
help="Exibe o lucro total do dia e encerra.",
|
|
40
|
+
)
|
|
41
|
+
def checar(limite: float, lucro: bool):
|
|
42
|
+
"""
|
|
43
|
+
Executa uma verificação pontual do risco diário.
|
|
44
|
+
"""
|
|
45
|
+
if lucro:
|
|
46
|
+
total = calcular_lucro_total_dia()
|
|
47
|
+
click.echo(f"Lucro total do dia: {total:.2f}")
|
|
48
|
+
log.info(f"[RISCO] Lucro total do dia: {total:.2f}")
|
|
49
|
+
return
|
|
50
|
+
|
|
51
|
+
hoje = date.today()
|
|
52
|
+
estado = carregar_estado(STATUS_FILE)
|
|
53
|
+
|
|
54
|
+
# Reset diário
|
|
55
|
+
if estado["data"] != hoje.isoformat():
|
|
56
|
+
log.info("[ESTADO] Novo dia detectado, resetando bloqueio.")
|
|
57
|
+
estado["bloqueado"] = False
|
|
58
|
+
salvar_estado(STATUS_FILE, hoje, False)
|
|
59
|
+
|
|
60
|
+
if estado["bloqueado"]:
|
|
61
|
+
click.echo("Sistema bloqueado hoje por limite de risco.")
|
|
62
|
+
log.warning("[RISCO] Sistema já bloqueado hoje.")
|
|
63
|
+
return
|
|
64
|
+
|
|
65
|
+
if risco_excedido(limite):
|
|
66
|
+
click.echo(
|
|
67
|
+
f"Limite {limite:.2f} excedido. Encerrando posições e bloqueando ordens."
|
|
68
|
+
)
|
|
69
|
+
log.warning(f"[RISCO] Limite {limite:.2f} excedido.")
|
|
70
|
+
encerrar_todas_posicoes()
|
|
71
|
+
cancelar_todas_ordens()
|
|
72
|
+
salvar_estado(STATUS_FILE, hoje, True)
|
|
73
|
+
else:
|
|
74
|
+
click.echo("Dentro do limite de risco.")
|
|
75
|
+
log.info(f"[RISCO] Dentro do limite {limite:.2f}.")
|
mtcli_risco-2.5.0/mtcli_risco/commands/trades.py → mtcli_risco-2.5.1/mtcli_risco/commands/lucro.py
RENAMED
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Comando
|
|
3
|
-
|
|
4
|
-
Exibe lucros realizados, abertos e totais do dia.
|
|
5
|
-
"""
|
|
6
|
-
|
|
7
|
-
import click
|
|
8
|
-
from mtcli.logger import setup_logger
|
|
9
|
-
from mtcli_risco.models.trades_model import (
|
|
10
|
-
obter_lucro_aberto,
|
|
11
|
-
calcular_lucro_realizado,
|
|
12
|
-
calcular_lucro_total_dia,
|
|
13
|
-
)
|
|
14
|
-
|
|
15
|
-
log = setup_logger()
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
@click.command(
|
|
19
|
-
"
|
|
20
|
-
help="Exibe os lucros realizados, abertos e totais do dia.",
|
|
21
|
-
)
|
|
22
|
-
@click.version_option(package_name="mtcli-risco")
|
|
23
|
-
@click.option("--aberto", "-a", is_flag=True, help="Exibe o lucro em aberto.")
|
|
24
|
-
@click.option("--realizado", "-r", is_flag=True, help="Exibe o lucro realizado.")
|
|
25
|
-
@click.option("--total", "-t", is_flag=True, help="Exibe o lucro total.")
|
|
26
|
-
def
|
|
27
|
-
"""
|
|
28
|
-
Exibe informações de lucro do dia atual.
|
|
29
|
-
"""
|
|
30
|
-
if aberto:
|
|
31
|
-
valor = obter_lucro_aberto()
|
|
32
|
-
click.echo(f"{valor:.2f}")
|
|
33
|
-
return
|
|
34
|
-
|
|
35
|
-
if realizado:
|
|
36
|
-
valor = calcular_lucro_realizado()
|
|
37
|
-
click.echo(f"{valor:.2f}")
|
|
38
|
-
return
|
|
39
|
-
|
|
40
|
-
if total:
|
|
41
|
-
valor = calcular_lucro_total_dia()
|
|
42
|
-
click.echo(f"{valor:.2f}")
|
|
43
|
-
return
|
|
44
|
-
|
|
45
|
-
aberto_v = obter_lucro_aberto()
|
|
46
|
-
realizado_v = calcular_lucro_realizado()
|
|
47
|
-
total_v = aberto_v + realizado_v
|
|
48
|
-
|
|
49
|
-
click.echo(f"lucro em aberto: {aberto_v:.2f}")
|
|
50
|
-
click.echo(f"lucro realizado: {realizado_v:.2f}")
|
|
51
|
-
click.echo(f"lucro total: {total_v:.2f}")
|
|
1
|
+
"""
|
|
2
|
+
Comando lucro.
|
|
3
|
+
|
|
4
|
+
Exibe lucros realizados, abertos e totais do dia.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
from mtcli.logger import setup_logger
|
|
9
|
+
from mtcli_risco.models.trades_model import (
|
|
10
|
+
obter_lucro_aberto,
|
|
11
|
+
calcular_lucro_realizado,
|
|
12
|
+
calcular_lucro_total_dia,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
log = setup_logger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@click.command(
|
|
19
|
+
"lucro",
|
|
20
|
+
help="Exibe os lucros realizados, abertos e totais do dia.",
|
|
21
|
+
)
|
|
22
|
+
@click.version_option(package_name="mtcli-risco")
|
|
23
|
+
@click.option("--aberto", "-a", is_flag=True, help="Exibe o lucro em aberto.")
|
|
24
|
+
@click.option("--realizado", "-r", is_flag=True, help="Exibe o lucro realizado.")
|
|
25
|
+
@click.option("--total", "-t", is_flag=True, help="Exibe o lucro total.")
|
|
26
|
+
def lucro(aberto: bool, realizado: bool, total: bool):
|
|
27
|
+
"""
|
|
28
|
+
Exibe informações de lucro do dia atual.
|
|
29
|
+
"""
|
|
30
|
+
if aberto:
|
|
31
|
+
valor = obter_lucro_aberto()
|
|
32
|
+
click.echo(f"{valor:.2f}")
|
|
33
|
+
return
|
|
34
|
+
|
|
35
|
+
if realizado:
|
|
36
|
+
valor = calcular_lucro_realizado()
|
|
37
|
+
click.echo(f"{valor:.2f}")
|
|
38
|
+
return
|
|
39
|
+
|
|
40
|
+
if total:
|
|
41
|
+
valor = calcular_lucro_total_dia()
|
|
42
|
+
click.echo(f"{valor:.2f}")
|
|
43
|
+
return
|
|
44
|
+
|
|
45
|
+
aberto_v = obter_lucro_aberto()
|
|
46
|
+
realizado_v = calcular_lucro_realizado()
|
|
47
|
+
total_v = aberto_v + realizado_v
|
|
48
|
+
|
|
49
|
+
click.echo(f"lucro em aberto: {aberto_v:.2f}")
|
|
50
|
+
click.echo(f"lucro realizado: {realizado_v:.2f}")
|
|
51
|
+
click.echo(f"lucro total: {total_v:.2f}")
|
|
@@ -17,7 +17,7 @@ from ..models.checar_model import (
|
|
|
17
17
|
)
|
|
18
18
|
from ..models.panic_model import panic_close_all
|
|
19
19
|
|
|
20
|
-
log = setup_logger(
|
|
20
|
+
log = setup_logger(__name__)
|
|
21
21
|
|
|
22
22
|
|
|
23
23
|
@click.command()
|
|
@@ -25,7 +25,7 @@ log = setup_logger("risco")
|
|
|
25
25
|
@click.option("--limite", "-l", default=LOSS_LIMIT, show_default=True)
|
|
26
26
|
@click.option("--intervalo", "-i", default=INTERVALO, show_default=True)
|
|
27
27
|
@click.option("--dry-run", is_flag=True, help="Simula o panic close.")
|
|
28
|
-
def
|
|
28
|
+
def monitorar(limite: float, intervalo: int, dry_run: bool):
|
|
29
29
|
"""
|
|
30
30
|
Inicia o monitoramento contínuo do risco diário.
|
|
31
31
|
"""
|
|
@@ -7,7 +7,7 @@ from mtcli.logger import setup_logger
|
|
|
7
7
|
from ..models.panic_model import panic_close_all
|
|
8
8
|
from mtcli_risco import conf
|
|
9
9
|
|
|
10
|
-
log = setup_logger(
|
|
10
|
+
log = setup_logger(__name__)
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
@click.command()
|
|
@@ -26,7 +26,7 @@ log = setup_logger("risco")
|
|
|
26
26
|
type=click.Path(exists=True),
|
|
27
27
|
help="Caminho do terminal MT5 (override temporário)",
|
|
28
28
|
)
|
|
29
|
-
def
|
|
29
|
+
def panic(no_retry: bool, dry_run: bool, terminal_path: str | None):
|
|
30
30
|
"""
|
|
31
31
|
Executa o PANIC CLOSE com HARDSTOP.
|
|
32
32
|
"""
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Comando start.
|
|
3
|
+
|
|
4
|
+
Responsável por iniciar o monitor de risco em background.
|
|
5
|
+
|
|
6
|
+
- Evita múltiplas instâncias (verificando PID ativo)
|
|
7
|
+
- Limpa PID inválido (processo morto)
|
|
8
|
+
- Inicia subprocesso com monitor_loop
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import click
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
import signal
|
|
17
|
+
|
|
18
|
+
from mtcli.logger import setup_logger
|
|
19
|
+
from mtcli.conf import PID_FILE
|
|
20
|
+
from ..conf import LOSS_LIMIT, INTERVALO
|
|
21
|
+
|
|
22
|
+
log = setup_logger("risco")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _pid_running(pid: int) -> bool:
|
|
26
|
+
"""
|
|
27
|
+
Verifica se um PID está ativo no sistema.
|
|
28
|
+
"""
|
|
29
|
+
try:
|
|
30
|
+
os.kill(pid, 0)
|
|
31
|
+
return True
|
|
32
|
+
except Exception:
|
|
33
|
+
return False
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@click.command()
|
|
37
|
+
@click.option("--limite", default=LOSS_LIMIT, show_default=True)
|
|
38
|
+
@click.option("--intervalo", default=INTERVALO, show_default=True)
|
|
39
|
+
@click.option("--dry-run", is_flag=True, help="Simula execução sem enviar ordens.")
|
|
40
|
+
def start(limite: float, intervalo: int, dry_run: bool) -> None:
|
|
41
|
+
"""
|
|
42
|
+
Inicia o monitor de risco em background.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
# ===============================
|
|
46
|
+
# Verifica PID existente
|
|
47
|
+
# ===============================
|
|
48
|
+
if os.path.exists(PID_FILE):
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
with open(PID_FILE) as f:
|
|
52
|
+
pid = int(f.read().strip())
|
|
53
|
+
|
|
54
|
+
if _pid_running(pid):
|
|
55
|
+
click.echo(f"Monitor já está rodando (PID {pid}).")
|
|
56
|
+
log.warning("[START] Monitor já ativo | pid=%s", pid)
|
|
57
|
+
return
|
|
58
|
+
else:
|
|
59
|
+
log.warning("[START] PID morto detectado, removendo | pid=%s", pid)
|
|
60
|
+
os.remove(PID_FILE)
|
|
61
|
+
|
|
62
|
+
except Exception as e:
|
|
63
|
+
log.error("[START] Erro ao ler PID_FILE | erro=%s", e)
|
|
64
|
+
os.remove(PID_FILE)
|
|
65
|
+
|
|
66
|
+
# ===============================
|
|
67
|
+
# Comando subprocesso
|
|
68
|
+
# ===============================
|
|
69
|
+
cmd = [
|
|
70
|
+
sys.executable,
|
|
71
|
+
"-m",
|
|
72
|
+
"mtcli_risco.services.run_monitor",
|
|
73
|
+
str(limite),
|
|
74
|
+
str(intervalo),
|
|
75
|
+
str(int(dry_run)),
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
log.info(
|
|
79
|
+
"[START] Iniciando monitor | limite=%.2f intervalo=%ss dry_run=%s",
|
|
80
|
+
limite,
|
|
81
|
+
intervalo,
|
|
82
|
+
dry_run,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
proc = subprocess.Popen(
|
|
86
|
+
cmd,
|
|
87
|
+
stdout=subprocess.DEVNULL,
|
|
88
|
+
stderr=subprocess.DEVNULL,
|
|
89
|
+
close_fds=True,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
time.sleep(1)
|
|
93
|
+
|
|
94
|
+
if proc.poll() is not None:
|
|
95
|
+
log.error("[START] Processo morreu imediatamente")
|
|
96
|
+
click.echo("Erro ao iniciar monitor (verifique logs).")
|
|
97
|
+
return
|
|
98
|
+
|
|
99
|
+
log.info("[START] Monitor iniciado | pid=%s", proc.pid)
|
|
100
|
+
|
|
101
|
+
click.echo(f"Monitor iniciado em background (PID {proc.pid}).")
|
|
@@ -23,11 +23,11 @@ import click
|
|
|
23
23
|
from mtcli.logger import setup_logger
|
|
24
24
|
from mtcli.conf import PID_FILE, HEARTBEAT_FILE
|
|
25
25
|
|
|
26
|
-
log = setup_logger(
|
|
26
|
+
log = setup_logger(__name__)
|
|
27
27
|
|
|
28
28
|
|
|
29
29
|
@click.command()
|
|
30
|
-
def
|
|
30
|
+
def status() -> None:
|
|
31
31
|
"""
|
|
32
32
|
Exibe o status atual do monitor de risco.
|
|
33
33
|
"""
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Comando stop.
|
|
3
|
+
|
|
4
|
+
Solicita a parada do monitor de risco.
|
|
5
|
+
|
|
6
|
+
Estratégia:
|
|
7
|
+
1. Envia sinal gracioso via STOP_FILE
|
|
8
|
+
2. Fallback: encerra processo via PID (SIGTERM ou taskkill)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import subprocess
|
|
13
|
+
import click
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
from mtcli.logger import setup_logger
|
|
17
|
+
from mtcli.conf import STOP_FILE, PID_FILE
|
|
18
|
+
|
|
19
|
+
log = setup_logger("risco")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _pid_running(pid: int) -> bool:
|
|
23
|
+
try:
|
|
24
|
+
os.kill(pid, 0)
|
|
25
|
+
return True
|
|
26
|
+
except Exception:
|
|
27
|
+
return False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@click.command()
|
|
31
|
+
def stop() -> None:
|
|
32
|
+
"""
|
|
33
|
+
Para o monitor de risco com garantia de finalização.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
# ===============================
|
|
37
|
+
# 1. STOP gracioso
|
|
38
|
+
# ===============================
|
|
39
|
+
try:
|
|
40
|
+
with open(STOP_FILE, "w") as f:
|
|
41
|
+
f.write("stop")
|
|
42
|
+
|
|
43
|
+
log.info("[STOP] STOP_FILE enviado")
|
|
44
|
+
click.echo("Sinal de parada enviado.")
|
|
45
|
+
|
|
46
|
+
except Exception as e:
|
|
47
|
+
log.error("[STOP] Erro ao criar STOP_FILE | erro=%s", e)
|
|
48
|
+
|
|
49
|
+
# ===============================
|
|
50
|
+
# 2. Aguarda parada graciosa
|
|
51
|
+
# ===============================
|
|
52
|
+
time.sleep(2)
|
|
53
|
+
|
|
54
|
+
# ===============================
|
|
55
|
+
# 3. Fallback: kill forçado
|
|
56
|
+
# ===============================
|
|
57
|
+
if os.path.exists(PID_FILE):
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
with open(PID_FILE) as f:
|
|
61
|
+
pid = int(f.read().strip())
|
|
62
|
+
|
|
63
|
+
if not _pid_running(pid):
|
|
64
|
+
click.echo("Processo já estava parado.")
|
|
65
|
+
return
|
|
66
|
+
|
|
67
|
+
log.warning("[STOP] Forçando encerramento | pid=%s", pid)
|
|
68
|
+
|
|
69
|
+
result = subprocess.run(
|
|
70
|
+
["taskkill", "/PID", str(pid), "/F", "/T"],
|
|
71
|
+
capture_output=True,
|
|
72
|
+
text=True,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
if result.returncode == 0:
|
|
76
|
+
log.warning("[STOP] Processo finalizado via taskkill | pid=%s", pid)
|
|
77
|
+
click.echo(f"Processo {pid} finalizado com sucesso.")
|
|
78
|
+
else:
|
|
79
|
+
log.error(
|
|
80
|
+
"[STOP] Falha no taskkill | pid=%s stderr=%s",
|
|
81
|
+
pid,
|
|
82
|
+
result.stderr.strip(),
|
|
83
|
+
)
|
|
84
|
+
click.echo("Erro ao finalizar processo. Verifique logs.")
|
|
85
|
+
|
|
86
|
+
except Exception as e:
|
|
87
|
+
log.error("[STOP] Erro ao matar processo | erro=%s", e)
|
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
import os
|
|
2
|
-
from mtcli.conf import config
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
LOSS_LIMIT = float(
|
|
6
|
-
os.getenv(
|
|
7
|
-
"LOSS_LIMIT",
|
|
8
|
-
config["DEFAULT"].getfloat("loss_limit", fallback=-180.00),
|
|
9
|
-
)
|
|
10
|
-
)
|
|
11
|
-
|
|
12
|
-
STATUS_FILE = os.getenv(
|
|
13
|
-
"STATUS_FILE",
|
|
14
|
-
config["DEFAULT"].get("status_file", fallback="bloqueio.json"),
|
|
15
|
-
)
|
|
16
|
-
|
|
17
|
-
INTERVALO = int(
|
|
18
|
-
os.getenv(
|
|
19
|
-
"INTERVALO",
|
|
20
|
-
config["DEFAULT"].getint("intervalo", fallback=1),
|
|
21
|
-
)
|
|
22
|
-
)
|
|
23
|
-
|
|
24
|
-
# Caminho do executável do MetaTrader 5 (usado no HARDSTOP)
|
|
25
|
-
MT5_TERMINAL_PATH = os.getenv(
|
|
26
|
-
"MT5_TERMINAL_PATH",
|
|
27
|
-
config["DEFAULT"].get(
|
|
28
|
-
"mt5_terminal_path",
|
|
29
|
-
fallback=r"C:\Program Files\MetaTrader 5\terminal64.exe",
|
|
30
|
-
),
|
|
31
|
-
)
|
|
1
|
+
import os
|
|
2
|
+
from mtcli.conf import config
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
LOSS_LIMIT = float(
|
|
6
|
+
os.getenv(
|
|
7
|
+
"LOSS_LIMIT",
|
|
8
|
+
config["DEFAULT"].getfloat("loss_limit", fallback=-180.00),
|
|
9
|
+
)
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
STATUS_FILE = os.getenv(
|
|
13
|
+
"STATUS_FILE",
|
|
14
|
+
config["DEFAULT"].get("status_file", fallback="bloqueio.json"),
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
INTERVALO = int(
|
|
18
|
+
os.getenv(
|
|
19
|
+
"INTERVALO",
|
|
20
|
+
config["DEFAULT"].getint("intervalo", fallback=1),
|
|
21
|
+
)
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
# Caminho do executável do MetaTrader 5 (usado no HARDSTOP)
|
|
25
|
+
MT5_TERMINAL_PATH = os.getenv(
|
|
26
|
+
"MT5_TERMINAL_PATH",
|
|
27
|
+
config["DEFAULT"].get(
|
|
28
|
+
"mt5_terminal_path",
|
|
29
|
+
fallback=r"C:\Program Files\MetaTrader 5\terminal64.exe",
|
|
30
|
+
),
|
|
31
|
+
)
|