mtcli-risco 2.3.0.dev2__tar.gz → 2.4.0__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.3.0.dev2 → mtcli_risco-2.4.0}/PKG-INFO +1 -1
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/cli.py +27 -27
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/commands/checar.py +75 -75
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/commands/monitorar.py +64 -64
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/commands/panic.py +36 -36
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/commands/trades.py +51 -51
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/models/checar_model.py +117 -117
- mtcli_risco-2.4.0/mtcli_risco/models/hardstop_model.py +117 -0
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/models/panic_model.py +13 -2
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/models/trades_model.py +62 -62
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/plugin.py +12 -12
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/pyproject.toml +1 -1
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/LICENSE +0 -0
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/README.md +0 -0
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/__init__.py +0 -0
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/commands/__init__.py +0 -0
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/conf.py +0 -0
- {mtcli_risco-2.3.0.dev2 → mtcli_risco-2.4.0}/mtcli_risco/models/__init__.py +0 -0
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Comando principal e registro dos subcomandos
|
|
3
|
-
"""
|
|
4
|
-
|
|
5
|
-
import click
|
|
6
|
-
from .commands.checar import checar_cmd
|
|
7
|
-
from .commands.monitorar import monitorar_cmd
|
|
8
|
-
from .commands.trades import trades_cmd
|
|
9
|
-
from .commands.panic import panic_cmd
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
@click.group()
|
|
13
|
-
@click.version_option(package_name="mtcli-risco")
|
|
14
|
-
def cli():
|
|
15
|
-
"""
|
|
16
|
-
Plugin mtcli-risco.
|
|
17
|
-
|
|
18
|
-
Conjunto de comandos para gerenciamento e controle de risco diário
|
|
19
|
-
baseado em lucro/prejuízo no MetaTrader 5.
|
|
20
|
-
"""
|
|
21
|
-
pass
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
cli.add_command(checar_cmd, name="checar")
|
|
25
|
-
cli.add_command(monitorar_cmd, name="monitorar")
|
|
26
|
-
cli.add_command(trades_cmd, name="trades")
|
|
27
|
-
cli.add_command(panic_cmd, name="panic")
|
|
1
|
+
"""
|
|
2
|
+
Comando principal e registro dos subcomandos
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
from .commands.checar import checar_cmd
|
|
7
|
+
from .commands.monitorar import monitorar_cmd
|
|
8
|
+
from .commands.trades import trades_cmd
|
|
9
|
+
from .commands.panic import panic_cmd
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@click.group()
|
|
13
|
+
@click.version_option(package_name="mtcli-risco")
|
|
14
|
+
def cli():
|
|
15
|
+
"""
|
|
16
|
+
Plugin mtcli-risco.
|
|
17
|
+
|
|
18
|
+
Conjunto de comandos para gerenciamento e controle de risco diário
|
|
19
|
+
baseado em lucro/prejuízo no MetaTrader 5.
|
|
20
|
+
"""
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
cli.add_command(checar_cmd, name="checar")
|
|
25
|
+
cli.add_command(monitorar_cmd, name="monitorar")
|
|
26
|
+
cli.add_command(trades_cmd, name="trades")
|
|
27
|
+
cli.add_command(panic_cmd, name="panic")
|
|
@@ -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 checar_cmd(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}.")
|
|
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 checar_cmd(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}.")
|
|
@@ -1,64 +1,64 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Comando monitorar.
|
|
3
|
-
|
|
4
|
-
Monitora continuamente o risco diário e executa PANIC CLOSE
|
|
5
|
-
quando o limite é excedido.
|
|
6
|
-
"""
|
|
7
|
-
|
|
8
|
-
import time
|
|
9
|
-
import click
|
|
10
|
-
from datetime import date
|
|
11
|
-
from mtcli.logger import setup_logger
|
|
12
|
-
from mtcli_risco.conf import LOSS_LIMIT, STATUS_FILE, INTERVALO
|
|
13
|
-
from mtcli_risco.models.checar_model import (
|
|
14
|
-
carregar_estado,
|
|
15
|
-
salvar_estado,
|
|
16
|
-
risco_excedido,
|
|
17
|
-
)
|
|
18
|
-
from mtcli_risco.models.panic_model import panic_close_all
|
|
19
|
-
|
|
20
|
-
log = setup_logger()
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
@click.command()
|
|
24
|
-
@click.version_option(package_name="mtcli-risco")
|
|
25
|
-
@click.option("--limite", "-l", default=LOSS_LIMIT, show_default=True)
|
|
26
|
-
@click.option("--intervalo", "-i", default=INTERVALO, show_default=True)
|
|
27
|
-
@click.option("--dry-run", is_flag=True, help="Simula o panic close.")
|
|
28
|
-
def monitorar_cmd(limite: float, intervalo: int, dry_run: bool):
|
|
29
|
-
"""
|
|
30
|
-
Inicia o monitoramento contínuo do risco diário.
|
|
31
|
-
"""
|
|
32
|
-
click.echo(
|
|
33
|
-
f"Monitorando risco | limite={limite:.2f} intervalo={intervalo}s"
|
|
34
|
-
)
|
|
35
|
-
log.info(
|
|
36
|
-
f"[MONITOR] Iniciado | limite={limite} intervalo={intervalo}s dry_run={dry_run}"
|
|
37
|
-
)
|
|
38
|
-
|
|
39
|
-
try:
|
|
40
|
-
while True:
|
|
41
|
-
hoje = date.today()
|
|
42
|
-
estado = carregar_estado(STATUS_FILE)
|
|
43
|
-
|
|
44
|
-
if estado["data"] != hoje.isoformat():
|
|
45
|
-
salvar_estado(STATUS_FILE, hoje, False)
|
|
46
|
-
estado["bloqueado"] = False
|
|
47
|
-
|
|
48
|
-
if not estado["bloqueado"] and risco_excedido(limite):
|
|
49
|
-
click.echo("LIMITE DE RISCO EXCEDIDO — PANIC CLOSE")
|
|
50
|
-
log.critical("[MONITOR] Disparando PANIC CLOSE")
|
|
51
|
-
|
|
52
|
-
resultado = panic_close_all(
|
|
53
|
-
retry_on_market_open=True,
|
|
54
|
-
dry_run=dry_run,
|
|
55
|
-
)
|
|
56
|
-
|
|
57
|
-
salvar_estado(STATUS_FILE, hoje, True)
|
|
58
|
-
log.critical(f"[MONITOR] Panic finalizado: {resultado}")
|
|
59
|
-
|
|
60
|
-
time.sleep(intervalo)
|
|
61
|
-
|
|
62
|
-
except KeyboardInterrupt:
|
|
63
|
-
click.echo("Monitoramento interrompido.")
|
|
64
|
-
log.info("[MONITOR] Interrompido pelo usuário.")
|
|
1
|
+
"""
|
|
2
|
+
Comando monitorar.
|
|
3
|
+
|
|
4
|
+
Monitora continuamente o risco diário e executa PANIC CLOSE
|
|
5
|
+
quando o limite é excedido.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import time
|
|
9
|
+
import click
|
|
10
|
+
from datetime import date
|
|
11
|
+
from mtcli.logger import setup_logger
|
|
12
|
+
from mtcli_risco.conf import LOSS_LIMIT, STATUS_FILE, INTERVALO
|
|
13
|
+
from mtcli_risco.models.checar_model import (
|
|
14
|
+
carregar_estado,
|
|
15
|
+
salvar_estado,
|
|
16
|
+
risco_excedido,
|
|
17
|
+
)
|
|
18
|
+
from mtcli_risco.models.panic_model import panic_close_all
|
|
19
|
+
|
|
20
|
+
log = setup_logger()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@click.command()
|
|
24
|
+
@click.version_option(package_name="mtcli-risco")
|
|
25
|
+
@click.option("--limite", "-l", default=LOSS_LIMIT, show_default=True)
|
|
26
|
+
@click.option("--intervalo", "-i", default=INTERVALO, show_default=True)
|
|
27
|
+
@click.option("--dry-run", is_flag=True, help="Simula o panic close.")
|
|
28
|
+
def monitorar_cmd(limite: float, intervalo: int, dry_run: bool):
|
|
29
|
+
"""
|
|
30
|
+
Inicia o monitoramento contínuo do risco diário.
|
|
31
|
+
"""
|
|
32
|
+
click.echo(
|
|
33
|
+
f"Monitorando risco | limite={limite:.2f} intervalo={intervalo}s"
|
|
34
|
+
)
|
|
35
|
+
log.info(
|
|
36
|
+
f"[MONITOR] Iniciado | limite={limite} intervalo={intervalo}s dry_run={dry_run}"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
while True:
|
|
41
|
+
hoje = date.today()
|
|
42
|
+
estado = carregar_estado(STATUS_FILE)
|
|
43
|
+
|
|
44
|
+
if estado["data"] != hoje.isoformat():
|
|
45
|
+
salvar_estado(STATUS_FILE, hoje, False)
|
|
46
|
+
estado["bloqueado"] = False
|
|
47
|
+
|
|
48
|
+
if not estado["bloqueado"] and risco_excedido(limite):
|
|
49
|
+
click.echo("LIMITE DE RISCO EXCEDIDO — PANIC CLOSE")
|
|
50
|
+
log.critical("[MONITOR] Disparando PANIC CLOSE")
|
|
51
|
+
|
|
52
|
+
resultado = panic_close_all(
|
|
53
|
+
retry_on_market_open=True,
|
|
54
|
+
dry_run=dry_run,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
salvar_estado(STATUS_FILE, hoje, True)
|
|
58
|
+
log.critical(f"[MONITOR] Panic finalizado: {resultado}")
|
|
59
|
+
|
|
60
|
+
time.sleep(intervalo)
|
|
61
|
+
|
|
62
|
+
except KeyboardInterrupt:
|
|
63
|
+
click.echo("Monitoramento interrompido.")
|
|
64
|
+
log.info("[MONITOR] Interrompido pelo usuário.")
|
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Comando panic.
|
|
3
|
-
|
|
4
|
-
Executa o PANIC CLOSE manualmente.
|
|
5
|
-
"""
|
|
6
|
-
|
|
7
|
-
import click
|
|
8
|
-
from mtcli.logger import setup_logger
|
|
9
|
-
from mtcli_risco.models.panic_model import panic_close_all
|
|
10
|
-
|
|
11
|
-
log = setup_logger()
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
@click.command()
|
|
15
|
-
@click.option("--dry-run", is_flag=True, help="Simula o panic close.")
|
|
16
|
-
@click.option(
|
|
17
|
-
"--no-retry",
|
|
18
|
-
is_flag=True,
|
|
19
|
-
help="Não repetir quando o market estiver fechado.",
|
|
20
|
-
)
|
|
21
|
-
def panic_cmd(dry_run: bool, no_retry: bool):
|
|
22
|
-
"""
|
|
23
|
-
Executa manualmente o fechamento emergencial de posições.
|
|
24
|
-
"""
|
|
25
|
-
click.echo("Executando PANIC CLOSE...")
|
|
26
|
-
log.critical(
|
|
27
|
-
f"[PANIC] Execução manual | dry_run={dry_run} retry={not no_retry}"
|
|
28
|
-
)
|
|
29
|
-
|
|
30
|
-
resultado = panic_close_all(
|
|
31
|
-
retry_on_market_open=not no_retry,
|
|
32
|
-
dry_run=dry_run,
|
|
33
|
-
)
|
|
34
|
-
|
|
35
|
-
click.echo("PANIC CLOSE finalizado.")
|
|
36
|
-
log.critical(f"[PANIC] Resultado: {resultado}")
|
|
1
|
+
"""
|
|
2
|
+
Comando panic.
|
|
3
|
+
|
|
4
|
+
Executa o PANIC CLOSE manualmente.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
from mtcli.logger import setup_logger
|
|
9
|
+
from mtcli_risco.models.panic_model import panic_close_all
|
|
10
|
+
|
|
11
|
+
log = setup_logger()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@click.command()
|
|
15
|
+
@click.option("--dry-run", is_flag=True, help="Simula o panic close.")
|
|
16
|
+
@click.option(
|
|
17
|
+
"--no-retry",
|
|
18
|
+
is_flag=True,
|
|
19
|
+
help="Não repetir quando o market estiver fechado.",
|
|
20
|
+
)
|
|
21
|
+
def panic_cmd(dry_run: bool, no_retry: bool):
|
|
22
|
+
"""
|
|
23
|
+
Executa manualmente o fechamento emergencial de posições.
|
|
24
|
+
"""
|
|
25
|
+
click.echo("Executando PANIC CLOSE...")
|
|
26
|
+
log.critical(
|
|
27
|
+
f"[PANIC] Execução manual | dry_run={dry_run} retry={not no_retry}"
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
resultado = panic_close_all(
|
|
31
|
+
retry_on_market_open=not no_retry,
|
|
32
|
+
dry_run=dry_run,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
click.echo("PANIC CLOSE finalizado.")
|
|
36
|
+
log.critical(f"[PANIC] Resultado: {resultado}")
|
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Comando trades.
|
|
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
|
-
"trades",
|
|
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 trades_cmd(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}")
|
|
1
|
+
"""
|
|
2
|
+
Comando trades.
|
|
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
|
+
"trades",
|
|
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 trades_cmd(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}")
|
|
@@ -1,117 +1,117 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Model de controle de risco.
|
|
3
|
-
|
|
4
|
-
Responsável por:
|
|
5
|
-
- persistência de estado diário
|
|
6
|
-
- verificação de limite de prejuízo
|
|
7
|
-
- encerramento de posições
|
|
8
|
-
- cancelamento de ordens
|
|
9
|
-
"""
|
|
10
|
-
|
|
11
|
-
import json
|
|
12
|
-
import os
|
|
13
|
-
from datetime import date
|
|
14
|
-
import MetaTrader5 as mt5
|
|
15
|
-
from mtcli.logger import setup_logger
|
|
16
|
-
from mtcli.mt5_context import mt5_conexao
|
|
17
|
-
from .trades_model import calcular_lucro_total_dia
|
|
18
|
-
|
|
19
|
-
log = setup_logger()
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
def carregar_estado(status_file: str) -> dict:
|
|
23
|
-
"""
|
|
24
|
-
Carrega o estado persistido do controle de risco.
|
|
25
|
-
"""
|
|
26
|
-
if os.path.exists(status_file):
|
|
27
|
-
with open(status_file, "r") as f:
|
|
28
|
-
log.info(f"[ESTADO] Carregando {status_file}")
|
|
29
|
-
return json.load(f)
|
|
30
|
-
return {"data": "", "bloqueado": False}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
def salvar_estado(status_file: str, data: date, bloqueado: bool) -> None:
|
|
34
|
-
"""
|
|
35
|
-
Persiste o estado diário do controle de risco.
|
|
36
|
-
"""
|
|
37
|
-
with open(status_file, "w") as f:
|
|
38
|
-
json.dump(
|
|
39
|
-
{"data": data.isoformat(), "bloqueado": bloqueado},
|
|
40
|
-
f,
|
|
41
|
-
indent=2,
|
|
42
|
-
)
|
|
43
|
-
log.info(f"[ESTADO] Salvo | data={data.isoformat()} bloqueado={bloqueado}")
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
def encerrar_todas_posicoes() -> None:
|
|
47
|
-
"""
|
|
48
|
-
Encerra todas as posições abertas no MT5.
|
|
49
|
-
"""
|
|
50
|
-
with mt5_conexao():
|
|
51
|
-
positions = mt5.positions_get()
|
|
52
|
-
|
|
53
|
-
if not positions:
|
|
54
|
-
log.info("[MT5] Nenhuma posição aberta.")
|
|
55
|
-
return
|
|
56
|
-
|
|
57
|
-
for pos in positions:
|
|
58
|
-
tipo_oposto = (
|
|
59
|
-
mt5.ORDER_TYPE_SELL
|
|
60
|
-
if pos.type == mt5.ORDER_TYPE_BUY
|
|
61
|
-
else mt5.ORDER_TYPE_BUY
|
|
62
|
-
)
|
|
63
|
-
|
|
64
|
-
ordem = {
|
|
65
|
-
"action": mt5.TRADE_ACTION_DEAL,
|
|
66
|
-
"symbol": pos.symbol,
|
|
67
|
-
"volume": pos.volume,
|
|
68
|
-
"type": tipo_oposto,
|
|
69
|
-
"position": pos.ticket,
|
|
70
|
-
"deviation": 10,
|
|
71
|
-
"magic": 1000,
|
|
72
|
-
"comment": "Fechamento por limite de risco",
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
log.warning(f"[MT5] Encerrando posição {pos.ticket}")
|
|
76
|
-
resultado = mt5.order_send(ordem)
|
|
77
|
-
|
|
78
|
-
if not resultado or resultado.retcode != mt5.TRADE_RETCODE_DONE:
|
|
79
|
-
log.error(f"[MT5] Falha ao fechar {pos.ticket}: {resultado}")
|
|
80
|
-
else:
|
|
81
|
-
log.info(f"[MT5] Posição {pos.ticket} encerrada.")
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
def cancelar_todas_ordens() -> None:
|
|
85
|
-
"""
|
|
86
|
-
Cancela todas as ordens pendentes.
|
|
87
|
-
"""
|
|
88
|
-
with mt5_conexao():
|
|
89
|
-
ordens = mt5.orders_get()
|
|
90
|
-
|
|
91
|
-
if not ordens:
|
|
92
|
-
log.info("[MT5] Nenhuma ordem pendente.")
|
|
93
|
-
return
|
|
94
|
-
|
|
95
|
-
for ordem in ordens:
|
|
96
|
-
resultado = mt5.order_delete(ordem.ticket)
|
|
97
|
-
if not resultado or resultado.retcode != mt5.TRADE_RETCODE_DONE:
|
|
98
|
-
log.error(f"[MT5] Falha ao cancelar ordem {ordem.ticket}")
|
|
99
|
-
else:
|
|
100
|
-
log.info(f"[MT5] Ordem {ordem.ticket} cancelada.")
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
def risco_excedido(limite: float) -> bool:
|
|
104
|
-
"""
|
|
105
|
-
Verifica se o prejuízo diário ultrapassou o limite configurado.
|
|
106
|
-
"""
|
|
107
|
-
try:
|
|
108
|
-
total = calcular_lucro_total_dia()
|
|
109
|
-
if total <= limite:
|
|
110
|
-
log.warning(
|
|
111
|
-
f"[RISCO] Excedido | resultado={total:.2f} limite={limite:.2f}"
|
|
112
|
-
)
|
|
113
|
-
return True
|
|
114
|
-
return False
|
|
115
|
-
except Exception as exc:
|
|
116
|
-
log.error(f"[RISCO] Erro ao verificar limite: {exc}")
|
|
117
|
-
return False
|
|
1
|
+
"""
|
|
2
|
+
Model de controle de risco.
|
|
3
|
+
|
|
4
|
+
Responsável por:
|
|
5
|
+
- persistência de estado diário
|
|
6
|
+
- verificação de limite de prejuízo
|
|
7
|
+
- encerramento de posições
|
|
8
|
+
- cancelamento de ordens
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
from datetime import date
|
|
14
|
+
import MetaTrader5 as mt5
|
|
15
|
+
from mtcli.logger import setup_logger
|
|
16
|
+
from mtcli.mt5_context import mt5_conexao
|
|
17
|
+
from .trades_model import calcular_lucro_total_dia
|
|
18
|
+
|
|
19
|
+
log = setup_logger()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def carregar_estado(status_file: str) -> dict:
|
|
23
|
+
"""
|
|
24
|
+
Carrega o estado persistido do controle de risco.
|
|
25
|
+
"""
|
|
26
|
+
if os.path.exists(status_file):
|
|
27
|
+
with open(status_file, "r") as f:
|
|
28
|
+
log.info(f"[ESTADO] Carregando {status_file}")
|
|
29
|
+
return json.load(f)
|
|
30
|
+
return {"data": "", "bloqueado": False}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def salvar_estado(status_file: str, data: date, bloqueado: bool) -> None:
|
|
34
|
+
"""
|
|
35
|
+
Persiste o estado diário do controle de risco.
|
|
36
|
+
"""
|
|
37
|
+
with open(status_file, "w") as f:
|
|
38
|
+
json.dump(
|
|
39
|
+
{"data": data.isoformat(), "bloqueado": bloqueado},
|
|
40
|
+
f,
|
|
41
|
+
indent=2,
|
|
42
|
+
)
|
|
43
|
+
log.info(f"[ESTADO] Salvo | data={data.isoformat()} bloqueado={bloqueado}")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def encerrar_todas_posicoes() -> None:
|
|
47
|
+
"""
|
|
48
|
+
Encerra todas as posições abertas no MT5.
|
|
49
|
+
"""
|
|
50
|
+
with mt5_conexao():
|
|
51
|
+
positions = mt5.positions_get()
|
|
52
|
+
|
|
53
|
+
if not positions:
|
|
54
|
+
log.info("[MT5] Nenhuma posição aberta.")
|
|
55
|
+
return
|
|
56
|
+
|
|
57
|
+
for pos in positions:
|
|
58
|
+
tipo_oposto = (
|
|
59
|
+
mt5.ORDER_TYPE_SELL
|
|
60
|
+
if pos.type == mt5.ORDER_TYPE_BUY
|
|
61
|
+
else mt5.ORDER_TYPE_BUY
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
ordem = {
|
|
65
|
+
"action": mt5.TRADE_ACTION_DEAL,
|
|
66
|
+
"symbol": pos.symbol,
|
|
67
|
+
"volume": pos.volume,
|
|
68
|
+
"type": tipo_oposto,
|
|
69
|
+
"position": pos.ticket,
|
|
70
|
+
"deviation": 10,
|
|
71
|
+
"magic": 1000,
|
|
72
|
+
"comment": "Fechamento por limite de risco",
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
log.warning(f"[MT5] Encerrando posição {pos.ticket}")
|
|
76
|
+
resultado = mt5.order_send(ordem)
|
|
77
|
+
|
|
78
|
+
if not resultado or resultado.retcode != mt5.TRADE_RETCODE_DONE:
|
|
79
|
+
log.error(f"[MT5] Falha ao fechar {pos.ticket}: {resultado}")
|
|
80
|
+
else:
|
|
81
|
+
log.info(f"[MT5] Posição {pos.ticket} encerrada.")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def cancelar_todas_ordens() -> None:
|
|
85
|
+
"""
|
|
86
|
+
Cancela todas as ordens pendentes.
|
|
87
|
+
"""
|
|
88
|
+
with mt5_conexao():
|
|
89
|
+
ordens = mt5.orders_get()
|
|
90
|
+
|
|
91
|
+
if not ordens:
|
|
92
|
+
log.info("[MT5] Nenhuma ordem pendente.")
|
|
93
|
+
return
|
|
94
|
+
|
|
95
|
+
for ordem in ordens:
|
|
96
|
+
resultado = mt5.order_delete(ordem.ticket)
|
|
97
|
+
if not resultado or resultado.retcode != mt5.TRADE_RETCODE_DONE:
|
|
98
|
+
log.error(f"[MT5] Falha ao cancelar ordem {ordem.ticket}")
|
|
99
|
+
else:
|
|
100
|
+
log.info(f"[MT5] Ordem {ordem.ticket} cancelada.")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def risco_excedido(limite: float) -> bool:
|
|
104
|
+
"""
|
|
105
|
+
Verifica se o prejuízo diário ultrapassou o limite configurado.
|
|
106
|
+
"""
|
|
107
|
+
try:
|
|
108
|
+
total = calcular_lucro_total_dia()
|
|
109
|
+
if total <= limite:
|
|
110
|
+
log.warning(
|
|
111
|
+
f"[RISCO] Excedido | resultado={total:.2f} limite={limite:.2f}"
|
|
112
|
+
)
|
|
113
|
+
return True
|
|
114
|
+
return False
|
|
115
|
+
except Exception as exc:
|
|
116
|
+
log.error(f"[RISCO] Erro ao verificar limite: {exc}")
|
|
117
|
+
return False
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Hardstop via Sistema Operacional (Windows).
|
|
3
|
+
|
|
4
|
+
Responsável por:
|
|
5
|
+
- Encerrar o processo do MetaTrader 5
|
|
6
|
+
- Bloquear tráfego de rede do terminal via Firewall
|
|
7
|
+
- Impedir qualquer novo envio de ordens após PANIC
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import subprocess
|
|
12
|
+
import signal
|
|
13
|
+
from mtcli.logger import setup_logger
|
|
14
|
+
|
|
15
|
+
log = setup_logger()
|
|
16
|
+
|
|
17
|
+
MT5_PROCESS_NAME = "terminal64.exe"
|
|
18
|
+
FIREWALL_RULE_NAME = "MT5_HARDSTOP_BLOCK"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _run(cmd: list[str]) -> bool:
|
|
22
|
+
"""
|
|
23
|
+
Executa comando no Windows.
|
|
24
|
+
"""
|
|
25
|
+
try:
|
|
26
|
+
subprocess.run(
|
|
27
|
+
cmd,
|
|
28
|
+
check=True,
|
|
29
|
+
stdout=subprocess.DEVNULL,
|
|
30
|
+
stderr=subprocess.DEVNULL,
|
|
31
|
+
shell=False,
|
|
32
|
+
)
|
|
33
|
+
return True
|
|
34
|
+
except subprocess.CalledProcessError as exc:
|
|
35
|
+
log.error(f"[HARDSTOP] Falha ao executar comando: {cmd} | {exc}")
|
|
36
|
+
return False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def kill_mt5_process() -> None:
|
|
40
|
+
"""
|
|
41
|
+
Encerra o processo do MetaTrader 5 à força.
|
|
42
|
+
"""
|
|
43
|
+
log.critical("[HARDSTOP] Encerrando processo do MT5")
|
|
44
|
+
|
|
45
|
+
_run(
|
|
46
|
+
[
|
|
47
|
+
"taskkill",
|
|
48
|
+
"/F", # força
|
|
49
|
+
"/IM",
|
|
50
|
+
MT5_PROCESS_NAME,
|
|
51
|
+
]
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def block_mt5_firewall() -> None:
|
|
56
|
+
"""
|
|
57
|
+
Bloqueia qualquer tráfego de rede do MT5 via Firewall do Windows.
|
|
58
|
+
"""
|
|
59
|
+
log.critical("[HARDSTOP] Bloqueando tráfego de rede do MT5 (Firewall)")
|
|
60
|
+
|
|
61
|
+
# Remove regra anterior se existir (idempotente)
|
|
62
|
+
_run(
|
|
63
|
+
[
|
|
64
|
+
"netsh",
|
|
65
|
+
"advfirewall",
|
|
66
|
+
"firewall",
|
|
67
|
+
"delete",
|
|
68
|
+
"rule",
|
|
69
|
+
f"name={FIREWALL_RULE_NAME}",
|
|
70
|
+
]
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
# Cria regra de bloqueio
|
|
74
|
+
_run(
|
|
75
|
+
[
|
|
76
|
+
"netsh",
|
|
77
|
+
"advfirewall",
|
|
78
|
+
"firewall",
|
|
79
|
+
"add",
|
|
80
|
+
"rule",
|
|
81
|
+
f"name={FIREWALL_RULE_NAME}",
|
|
82
|
+
"dir=out",
|
|
83
|
+
"action=block",
|
|
84
|
+
f"program=%ProgramFiles%\\MetaTrader 5\\terminal64.exe",
|
|
85
|
+
"enable=yes",
|
|
86
|
+
]
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def unblock_mt5_firewall() -> None:
|
|
91
|
+
"""
|
|
92
|
+
Remove o bloqueio de firewall do MT5 (uso manual).
|
|
93
|
+
"""
|
|
94
|
+
log.warning("[HARDSTOP] Removendo bloqueio de firewall do MT5")
|
|
95
|
+
|
|
96
|
+
_run(
|
|
97
|
+
[
|
|
98
|
+
"netsh",
|
|
99
|
+
"advfirewall",
|
|
100
|
+
"firewall",
|
|
101
|
+
"delete",
|
|
102
|
+
"rule",
|
|
103
|
+
f"name={FIREWALL_RULE_NAME}",
|
|
104
|
+
]
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def hardstop() -> None:
|
|
109
|
+
"""
|
|
110
|
+
Executa o HARDSTOP completo:
|
|
111
|
+
- Mata o MT5
|
|
112
|
+
- Bloqueia rede via Firewall
|
|
113
|
+
"""
|
|
114
|
+
log.critical("========== HARDSTOP ACIONADO ==========")
|
|
115
|
+
kill_mt5_process()
|
|
116
|
+
block_mt5_firewall()
|
|
117
|
+
log.critical("========== MT5 TOTALMENTE BLOQUEADO ==========")
|
|
@@ -6,12 +6,15 @@ Responsável por:
|
|
|
6
6
|
- Cancelar TODAS as ordens pendentes
|
|
7
7
|
- Funcionar com market aberto ou fechado (retry automático)
|
|
8
8
|
- Suportar modo DRY-RUN (simulação)
|
|
9
|
+
- Acionar HARDSTOP via Sistema Operacional (Windows)
|
|
9
10
|
"""
|
|
10
11
|
|
|
11
12
|
import time
|
|
12
13
|
import MetaTrader5 as mt5
|
|
14
|
+
|
|
13
15
|
from mtcli.logger import setup_logger
|
|
14
16
|
from mtcli.mt5_context import mt5_conexao
|
|
17
|
+
from mtcli_risco.models.hardstop_model import hardstop
|
|
15
18
|
|
|
16
19
|
log = setup_logger()
|
|
17
20
|
|
|
@@ -64,7 +67,7 @@ def _close_position(position, dry_run: bool = False) -> bool:
|
|
|
64
67
|
"type_filling": mt5.ORDER_FILLING_IOC,
|
|
65
68
|
}
|
|
66
69
|
|
|
67
|
-
# Conta hedge →
|
|
70
|
+
# Conta hedge → fechamento por ticket
|
|
68
71
|
if position.ticket:
|
|
69
72
|
request["position"] = position.ticket
|
|
70
73
|
|
|
@@ -123,6 +126,7 @@ def panic_close_all(
|
|
|
123
126
|
"market_closed": False,
|
|
124
127
|
"trade_disabled": False,
|
|
125
128
|
"dry_run": dry_run,
|
|
129
|
+
"hardstop_executed": False,
|
|
126
130
|
}
|
|
127
131
|
|
|
128
132
|
while True:
|
|
@@ -132,7 +136,7 @@ def panic_close_all(
|
|
|
132
136
|
if not _trade_permitido():
|
|
133
137
|
log.critical("[PANIC] Trading desabilitado na conta!")
|
|
134
138
|
stats["trade_disabled"] = True
|
|
135
|
-
|
|
139
|
+
break
|
|
136
140
|
|
|
137
141
|
positions = mt5.positions_get()
|
|
138
142
|
orders = mt5.orders_get()
|
|
@@ -202,5 +206,12 @@ def panic_close_all(
|
|
|
202
206
|
)
|
|
203
207
|
time.sleep(retry_interval)
|
|
204
208
|
|
|
209
|
+
# 3️⃣ HARDSTOP via Sistema Operacional
|
|
210
|
+
if not dry_run:
|
|
211
|
+
hardstop()
|
|
212
|
+
stats["hardstop_executed"] = True
|
|
213
|
+
else:
|
|
214
|
+
log.warning("[PANIC][DRY] HARDSTOP não executado (modo simulação)")
|
|
215
|
+
|
|
205
216
|
log.critical(f"[PANIC] Resultado final: {stats}")
|
|
206
217
|
return stats
|
|
@@ -1,62 +1,62 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Model de cálculos de lucro diário.
|
|
3
|
-
"""
|
|
4
|
-
|
|
5
|
-
import MetaTrader5 as mt5
|
|
6
|
-
from datetime import datetime, time
|
|
7
|
-
from mtcli.logger import setup_logger
|
|
8
|
-
from mtcli.mt5_context import mt5_conexao
|
|
9
|
-
|
|
10
|
-
log = setup_logger()
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def calcular_lucro_realizado() -> float:
|
|
14
|
-
"""
|
|
15
|
-
Calcula o lucro/prejuízo realizado no dia atual.
|
|
16
|
-
"""
|
|
17
|
-
hoje = datetime.now().date()
|
|
18
|
-
inicio = datetime.combine(hoje, time(0, 0))
|
|
19
|
-
fim = datetime.combine(hoje, time(23, 59))
|
|
20
|
-
|
|
21
|
-
with mt5_conexao():
|
|
22
|
-
deals = mt5.history_deals_get(inicio, fim)
|
|
23
|
-
|
|
24
|
-
if not deals:
|
|
25
|
-
log.info("[TRADES] Nenhum deal realizado hoje.")
|
|
26
|
-
return 0.0
|
|
27
|
-
|
|
28
|
-
lucro = sum(
|
|
29
|
-
deal.profit for deal in deals if deal.entry == mt5.DEAL_ENTRY_OUT
|
|
30
|
-
)
|
|
31
|
-
|
|
32
|
-
log.info(f"[TRADES] Lucro realizado: {lucro:.2f}")
|
|
33
|
-
return lucro
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
def obter_lucro_aberto() -> float:
|
|
37
|
-
"""
|
|
38
|
-
Obtém o lucro/prejuízo das posições atualmente abertas.
|
|
39
|
-
"""
|
|
40
|
-
with mt5_conexao():
|
|
41
|
-
info = mt5.account_info()
|
|
42
|
-
|
|
43
|
-
if not info:
|
|
44
|
-
log.warning("[TRADES] account_info indisponível.")
|
|
45
|
-
return 0.0
|
|
46
|
-
|
|
47
|
-
log.info(f"[TRADES] Lucro em aberto: {info.profit:.2f}")
|
|
48
|
-
return info.profit
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
def calcular_lucro_total_dia() -> float:
|
|
52
|
-
"""
|
|
53
|
-
Calcula o lucro total do dia (realizado + aberto).
|
|
54
|
-
"""
|
|
55
|
-
realizado = calcular_lucro_realizado()
|
|
56
|
-
aberto = obter_lucro_aberto()
|
|
57
|
-
total = realizado + aberto
|
|
58
|
-
|
|
59
|
-
log.info(
|
|
60
|
-
f"[TRADES] Total do dia | realizado={realizado:.2f} aberto={aberto:.2f}"
|
|
61
|
-
)
|
|
62
|
-
return total
|
|
1
|
+
"""
|
|
2
|
+
Model de cálculos de lucro diário.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import MetaTrader5 as mt5
|
|
6
|
+
from datetime import datetime, time
|
|
7
|
+
from mtcli.logger import setup_logger
|
|
8
|
+
from mtcli.mt5_context import mt5_conexao
|
|
9
|
+
|
|
10
|
+
log = setup_logger()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def calcular_lucro_realizado() -> float:
|
|
14
|
+
"""
|
|
15
|
+
Calcula o lucro/prejuízo realizado no dia atual.
|
|
16
|
+
"""
|
|
17
|
+
hoje = datetime.now().date()
|
|
18
|
+
inicio = datetime.combine(hoje, time(0, 0))
|
|
19
|
+
fim = datetime.combine(hoje, time(23, 59))
|
|
20
|
+
|
|
21
|
+
with mt5_conexao():
|
|
22
|
+
deals = mt5.history_deals_get(inicio, fim)
|
|
23
|
+
|
|
24
|
+
if not deals:
|
|
25
|
+
log.info("[TRADES] Nenhum deal realizado hoje.")
|
|
26
|
+
return 0.0
|
|
27
|
+
|
|
28
|
+
lucro = sum(
|
|
29
|
+
deal.profit for deal in deals if deal.entry == mt5.DEAL_ENTRY_OUT
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
log.info(f"[TRADES] Lucro realizado: {lucro:.2f}")
|
|
33
|
+
return lucro
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def obter_lucro_aberto() -> float:
|
|
37
|
+
"""
|
|
38
|
+
Obtém o lucro/prejuízo das posições atualmente abertas.
|
|
39
|
+
"""
|
|
40
|
+
with mt5_conexao():
|
|
41
|
+
info = mt5.account_info()
|
|
42
|
+
|
|
43
|
+
if not info:
|
|
44
|
+
log.warning("[TRADES] account_info indisponível.")
|
|
45
|
+
return 0.0
|
|
46
|
+
|
|
47
|
+
log.info(f"[TRADES] Lucro em aberto: {info.profit:.2f}")
|
|
48
|
+
return info.profit
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def calcular_lucro_total_dia() -> float:
|
|
52
|
+
"""
|
|
53
|
+
Calcula o lucro total do dia (realizado + aberto).
|
|
54
|
+
"""
|
|
55
|
+
realizado = calcular_lucro_realizado()
|
|
56
|
+
aberto = obter_lucro_aberto()
|
|
57
|
+
total = realizado + aberto
|
|
58
|
+
|
|
59
|
+
log.info(
|
|
60
|
+
f"[TRADES] Total do dia | realizado={realizado:.2f} aberto={aberto:.2f}"
|
|
61
|
+
)
|
|
62
|
+
return total
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Registro do plugin mtcli-risco no mtcli principal.
|
|
3
|
-
"""
|
|
4
|
-
|
|
5
|
-
from .cli import cli as risco
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
def register(main_cli):
|
|
9
|
-
"""
|
|
10
|
-
Registra o grupo de comandos 'risco' no mtcli principal.
|
|
11
|
-
"""
|
|
12
|
-
main_cli.add_command(risco, name="risco")
|
|
1
|
+
"""
|
|
2
|
+
Registro do plugin mtcli-risco no mtcli principal.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from .cli import cli as risco
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def register(main_cli):
|
|
9
|
+
"""
|
|
10
|
+
Registra o grupo de comandos 'risco' no mtcli principal.
|
|
11
|
+
"""
|
|
12
|
+
main_cli.add_command(risco, name="risco")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|