mtcli-risco 2.2.2__tar.gz → 2.3.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.2.2 → mtcli_risco-2.3.0}/PKG-INFO +6 -4
- mtcli_risco-2.3.0/mtcli_risco/cli.py +27 -0
- {mtcli_risco-2.2.2 → mtcli_risco-2.3.0}/mtcli_risco/commands/checar.py +26 -22
- mtcli_risco-2.3.0/mtcli_risco/commands/monitorar.py +64 -0
- mtcli_risco-2.3.0/mtcli_risco/commands/panic.py +36 -0
- mtcli_risco-2.3.0/mtcli_risco/commands/trades.py +51 -0
- mtcli_risco-2.3.0/mtcli_risco/models/__init__.py +0 -0
- mtcli_risco-2.3.0/mtcli_risco/models/checar_model.py +117 -0
- mtcli_risco-2.3.0/mtcli_risco/models/panic_model.py +206 -0
- mtcli_risco-2.3.0/mtcli_risco/models/trades_model.py +62 -0
- mtcli_risco-2.3.0/mtcli_risco/plugin.py +12 -0
- {mtcli_risco-2.2.2 → mtcli_risco-2.3.0}/pyproject.toml +5 -3
- mtcli_risco-2.2.2/mtcli_risco/commands/__init__.py +0 -2
- mtcli_risco-2.2.2/mtcli_risco/commands/monitorar.py +0 -59
- mtcli_risco-2.2.2/mtcli_risco/commands/trades.py +0 -56
- mtcli_risco-2.2.2/mtcli_risco/models/checar_model.py +0 -102
- mtcli_risco-2.2.2/mtcli_risco/models/trades_model.py +0 -77
- mtcli_risco-2.2.2/mtcli_risco/mt5_context.py +0 -11
- mtcli_risco-2.2.2/mtcli_risco/plugin.py +0 -11
- {mtcli_risco-2.2.2 → mtcli_risco-2.3.0}/LICENSE +0 -0
- {mtcli_risco-2.2.2 → mtcli_risco-2.3.0}/README.md +0 -0
- {mtcli_risco-2.2.2 → mtcli_risco-2.3.0}/mtcli_risco/__init__.py +0 -0
- {mtcli_risco-2.2.2/mtcli_risco/models → mtcli_risco-2.3.0/mtcli_risco/commands}/__init__.py +0 -0
- {mtcli_risco-2.2.2 → mtcli_risco-2.3.0}/mtcli_risco/conf.py +0 -0
|
@@ -1,17 +1,19 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: mtcli-risco
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.0
|
|
4
4
|
Summary: Plugin mtcli para controle de loss diário
|
|
5
|
-
License: GPL-3.0
|
|
5
|
+
License-Expression: GPL-3.0
|
|
6
|
+
License-File: LICENSE
|
|
6
7
|
Author: Valmir França da Silva
|
|
7
8
|
Author-email: vfranca3@gmail.com
|
|
8
9
|
Requires-Python: >=3.10,<3.14
|
|
9
|
-
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
|
10
10
|
Classifier: Programming Language :: Python :: 3
|
|
11
11
|
Classifier: Programming Language :: Python :: 3.10
|
|
12
12
|
Classifier: Programming Language :: Python :: 3.11
|
|
13
13
|
Classifier: Programming Language :: Python :: 3.12
|
|
14
14
|
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Requires-Dist: click (>=8.3.1,<9.0.0)
|
|
16
|
+
Requires-Dist: metatrader5 (>=5.0.5572,<6.0.0)
|
|
15
17
|
Requires-Dist: mtcli (>=1.18.1)
|
|
16
18
|
Project-URL: Documentation, https://mtcli-risco.readthedocs.io
|
|
17
19
|
Project-URL: Homepage, https://github.com/vfranca/mtcli-risco
|
|
@@ -0,0 +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,4 +1,9 @@
|
|
|
1
|
-
"""
|
|
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
|
+
"""
|
|
2
7
|
|
|
3
8
|
import click
|
|
4
9
|
from datetime import date
|
|
@@ -13,59 +18,58 @@ from mtcli_risco.models.checar_model import (
|
|
|
13
18
|
cancelar_todas_ordens,
|
|
14
19
|
)
|
|
15
20
|
|
|
16
|
-
|
|
17
21
|
log = setup_logger()
|
|
18
22
|
|
|
19
23
|
|
|
20
24
|
@click.command(
|
|
21
25
|
"checar",
|
|
22
|
-
help="Verifica se o limite diário de prejuízo foi atingido
|
|
26
|
+
help="Verifica se o limite diário de prejuízo foi atingido.",
|
|
23
27
|
)
|
|
24
28
|
@click.version_option(package_name="mtcli-risco")
|
|
25
29
|
@click.option(
|
|
26
30
|
"--limite",
|
|
27
31
|
"-l",
|
|
28
32
|
default=LOSS_LIMIT,
|
|
29
|
-
help="Limite de perda diária (ex: -500)
|
|
33
|
+
help="Limite de perda diária (ex: -500).",
|
|
30
34
|
)
|
|
31
35
|
@click.option(
|
|
32
36
|
"--lucro",
|
|
33
37
|
is_flag=True,
|
|
34
38
|
default=False,
|
|
35
|
-
help="Exibe o lucro total do dia
|
|
39
|
+
help="Exibe o lucro total do dia e encerra.",
|
|
36
40
|
)
|
|
37
|
-
def
|
|
38
|
-
"""
|
|
41
|
+
def checar_cmd(limite: float, lucro: bool):
|
|
42
|
+
"""
|
|
43
|
+
Executa uma verificação pontual do risco diário.
|
|
44
|
+
"""
|
|
39
45
|
if lucro:
|
|
40
|
-
|
|
41
|
-
click.echo(f"Lucro total do dia: {
|
|
42
|
-
log.info(f"Lucro total do dia: {
|
|
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}")
|
|
43
49
|
return
|
|
44
50
|
|
|
45
|
-
estado = carregar_estado(STATUS_FILE)
|
|
46
51
|
hoje = date.today()
|
|
52
|
+
estado = carregar_estado(STATUS_FILE)
|
|
47
53
|
|
|
54
|
+
# Reset diário
|
|
48
55
|
if estado["data"] != hoje.isoformat():
|
|
56
|
+
log.info("[ESTADO] Novo dia detectado, resetando bloqueio.")
|
|
49
57
|
estado["bloqueado"] = False
|
|
58
|
+
salvar_estado(STATUS_FILE, hoje, False)
|
|
50
59
|
|
|
51
60
|
if estado["bloqueado"]:
|
|
52
|
-
click.echo("
|
|
61
|
+
click.echo("Sistema bloqueado hoje por limite de risco.")
|
|
62
|
+
log.warning("[RISCO] Sistema já bloqueado hoje.")
|
|
53
63
|
return
|
|
54
64
|
|
|
55
65
|
if risco_excedido(limite):
|
|
56
66
|
click.echo(
|
|
57
|
-
f"Limite {limite:.2f} excedido. Encerrando posições e bloqueando
|
|
67
|
+
f"Limite {limite:.2f} excedido. Encerrando posições e bloqueando ordens."
|
|
58
68
|
)
|
|
59
|
-
log.
|
|
69
|
+
log.warning(f"[RISCO] Limite {limite:.2f} excedido.")
|
|
60
70
|
encerrar_todas_posicoes()
|
|
61
71
|
cancelar_todas_ordens()
|
|
62
|
-
|
|
72
|
+
salvar_estado(STATUS_FILE, hoje, True)
|
|
63
73
|
else:
|
|
64
74
|
click.echo("Dentro do limite de risco.")
|
|
65
|
-
log.info(f"
|
|
66
|
-
|
|
67
|
-
salvar_estado(STATUS_FILE, hoje, estado["bloqueado"])
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if __name__ == "__main__":
|
|
71
|
-
checar()
|
|
75
|
+
log.info(f"[RISCO] Dentro do limite {limite:.2f}.")
|
|
@@ -0,0 +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.")
|
|
@@ -0,0 +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}")
|
|
@@ -0,0 +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}")
|
|
File without changes
|
|
@@ -0,0 +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
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Modo PANIC CLOSE.
|
|
3
|
+
|
|
4
|
+
Responsável por:
|
|
5
|
+
- Encerrar TODAS as posições abertas (hedge ou netting)
|
|
6
|
+
- Cancelar TODAS as ordens pendentes
|
|
7
|
+
- Funcionar com market aberto ou fechado (retry automático)
|
|
8
|
+
- Suportar modo DRY-RUN (simulação)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import time
|
|
12
|
+
import MetaTrader5 as mt5
|
|
13
|
+
from mtcli.logger import setup_logger
|
|
14
|
+
from mtcli.mt5_context import mt5_conexao
|
|
15
|
+
|
|
16
|
+
log = setup_logger()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _trade_permitido() -> bool:
|
|
20
|
+
"""
|
|
21
|
+
Verifica se a conta permite trading.
|
|
22
|
+
"""
|
|
23
|
+
info = mt5.account_info()
|
|
24
|
+
return bool(info and info.trade_allowed)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _market_aberto(symbol: str) -> bool:
|
|
28
|
+
"""
|
|
29
|
+
Verifica se o mercado do símbolo está aberto para trading.
|
|
30
|
+
"""
|
|
31
|
+
info = mt5.symbol_info(symbol)
|
|
32
|
+
return bool(info and info.trade_mode == mt5.SYMBOL_TRADE_MODE_FULL)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _close_position(position, dry_run: bool = False) -> bool:
|
|
36
|
+
"""
|
|
37
|
+
Fecha uma posição individual (compatível com hedge e netting).
|
|
38
|
+
"""
|
|
39
|
+
symbol = position.symbol
|
|
40
|
+
tick = mt5.symbol_info_tick(symbol)
|
|
41
|
+
|
|
42
|
+
if not tick:
|
|
43
|
+
log.error(f"[PANIC] Tick indisponível para {symbol}")
|
|
44
|
+
return False
|
|
45
|
+
|
|
46
|
+
order_type = (
|
|
47
|
+
mt5.ORDER_TYPE_SELL
|
|
48
|
+
if position.type == mt5.ORDER_TYPE_BUY
|
|
49
|
+
else mt5.ORDER_TYPE_BUY
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
price = tick.bid if order_type == mt5.ORDER_TYPE_SELL else tick.ask
|
|
53
|
+
|
|
54
|
+
request = {
|
|
55
|
+
"action": mt5.TRADE_ACTION_DEAL,
|
|
56
|
+
"symbol": symbol,
|
|
57
|
+
"volume": position.volume,
|
|
58
|
+
"type": order_type,
|
|
59
|
+
"price": price,
|
|
60
|
+
"deviation": 20,
|
|
61
|
+
"magic": 999999,
|
|
62
|
+
"comment": "PANIC CLOSE",
|
|
63
|
+
"type_time": mt5.ORDER_TIME_GTC,
|
|
64
|
+
"type_filling": mt5.ORDER_FILLING_IOC,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
# Conta hedge → precisa do ticket
|
|
68
|
+
if position.ticket:
|
|
69
|
+
request["position"] = position.ticket
|
|
70
|
+
|
|
71
|
+
if dry_run:
|
|
72
|
+
log.warning(f"[PANIC][DRY] Fechamento simulado: {request}")
|
|
73
|
+
return True
|
|
74
|
+
|
|
75
|
+
result = mt5.order_send(request)
|
|
76
|
+
|
|
77
|
+
if not result:
|
|
78
|
+
log.error(
|
|
79
|
+
f"[PANIC] order_send retornou None | "
|
|
80
|
+
f"{symbol} | last_error={mt5.last_error()}"
|
|
81
|
+
)
|
|
82
|
+
return False
|
|
83
|
+
|
|
84
|
+
if result.retcode != mt5.TRADE_RETCODE_DONE:
|
|
85
|
+
log.error(
|
|
86
|
+
f"[PANIC] Falha ao fechar posição {symbol} | "
|
|
87
|
+
f"retcode={result.retcode}"
|
|
88
|
+
)
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
log.critical(
|
|
92
|
+
f"[PANIC] Posição fechada | {symbol} vol={position.volume}"
|
|
93
|
+
)
|
|
94
|
+
return True
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def panic_close_all(
|
|
98
|
+
retry_on_market_open: bool = True,
|
|
99
|
+
retry_interval: int = 60,
|
|
100
|
+
dry_run: bool = False,
|
|
101
|
+
) -> dict:
|
|
102
|
+
"""
|
|
103
|
+
Executa o fechamento emergencial de TODAS as posições e ordens.
|
|
104
|
+
|
|
105
|
+
Parâmetros
|
|
106
|
+
----------
|
|
107
|
+
retry_on_market_open : bool
|
|
108
|
+
Reexecuta automaticamente quando o market estiver fechado.
|
|
109
|
+
retry_interval : int
|
|
110
|
+
Intervalo (segundos) entre tentativas quando market fechado.
|
|
111
|
+
dry_run : bool
|
|
112
|
+
Simula as ações sem enviar ordens reais.
|
|
113
|
+
|
|
114
|
+
Retorna
|
|
115
|
+
-------
|
|
116
|
+
dict
|
|
117
|
+
Estatísticas da execução do panic close.
|
|
118
|
+
"""
|
|
119
|
+
stats = {
|
|
120
|
+
"positions_total": 0,
|
|
121
|
+
"positions_closed": 0,
|
|
122
|
+
"orders_cancelled": 0,
|
|
123
|
+
"market_closed": False,
|
|
124
|
+
"trade_disabled": False,
|
|
125
|
+
"dry_run": dry_run,
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
while True:
|
|
129
|
+
market_fechado = False
|
|
130
|
+
|
|
131
|
+
with mt5_conexao():
|
|
132
|
+
if not _trade_permitido():
|
|
133
|
+
log.critical("[PANIC] Trading desabilitado na conta!")
|
|
134
|
+
stats["trade_disabled"] = True
|
|
135
|
+
return stats
|
|
136
|
+
|
|
137
|
+
positions = mt5.positions_get()
|
|
138
|
+
orders = mt5.orders_get()
|
|
139
|
+
|
|
140
|
+
if positions:
|
|
141
|
+
stats["positions_total"] = len(positions)
|
|
142
|
+
|
|
143
|
+
# 1️⃣ Fechamento de posições
|
|
144
|
+
if positions:
|
|
145
|
+
for pos in positions:
|
|
146
|
+
if not _market_aberto(pos.symbol):
|
|
147
|
+
market_fechado = True
|
|
148
|
+
log.critical(
|
|
149
|
+
f"[PANIC] Market fechado para {pos.symbol}"
|
|
150
|
+
)
|
|
151
|
+
continue
|
|
152
|
+
|
|
153
|
+
if _close_position(pos, dry_run=dry_run):
|
|
154
|
+
stats["positions_closed"] += 1
|
|
155
|
+
|
|
156
|
+
# 2️⃣ Cancelamento de ordens pendentes
|
|
157
|
+
if orders:
|
|
158
|
+
for ordem in orders:
|
|
159
|
+
if dry_run:
|
|
160
|
+
log.warning(
|
|
161
|
+
f"[PANIC][DRY] Cancelamento simulado | "
|
|
162
|
+
f"ticket={ordem.ticket}"
|
|
163
|
+
)
|
|
164
|
+
stats["orders_cancelled"] += 1
|
|
165
|
+
continue
|
|
166
|
+
|
|
167
|
+
request = {
|
|
168
|
+
"action": mt5.TRADE_ACTION_REMOVE,
|
|
169
|
+
"order": ordem.ticket,
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
result = mt5.order_send(request)
|
|
173
|
+
|
|
174
|
+
if not result:
|
|
175
|
+
log.error(
|
|
176
|
+
f"[PANIC] Falha ao cancelar ordem {ordem.ticket} | "
|
|
177
|
+
f"last_error={mt5.last_error()}"
|
|
178
|
+
)
|
|
179
|
+
continue
|
|
180
|
+
|
|
181
|
+
if result.retcode == mt5.TRADE_RETCODE_DONE:
|
|
182
|
+
stats["orders_cancelled"] += 1
|
|
183
|
+
log.warning(
|
|
184
|
+
f"[PANIC] Ordem cancelada | ticket={ordem.ticket}"
|
|
185
|
+
)
|
|
186
|
+
else:
|
|
187
|
+
log.error(
|
|
188
|
+
f"[PANIC] Falha ao cancelar ordem {ordem.ticket} | "
|
|
189
|
+
f"retcode={result.retcode}"
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
if not market_fechado:
|
|
193
|
+
break
|
|
194
|
+
|
|
195
|
+
stats["market_closed"] = True
|
|
196
|
+
|
|
197
|
+
if not retry_on_market_open:
|
|
198
|
+
break
|
|
199
|
+
|
|
200
|
+
log.critical(
|
|
201
|
+
f"[PANIC] Market fechado. Nova tentativa em {retry_interval}s..."
|
|
202
|
+
)
|
|
203
|
+
time.sleep(retry_interval)
|
|
204
|
+
|
|
205
|
+
log.critical(f"[PANIC] Resultado final: {stats}")
|
|
206
|
+
return stats
|
|
@@ -0,0 +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,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "mtcli-risco"
|
|
3
|
-
version = "2.
|
|
3
|
+
version = "2.3.0"
|
|
4
4
|
description = "Plugin mtcli para controle de loss diário"
|
|
5
5
|
authors = [
|
|
6
6
|
{name = "Valmir França da Silva",email = "vfranca3@gmail.com"}
|
|
@@ -9,7 +9,9 @@ readme = "README.md"
|
|
|
9
9
|
license = "GPL-3.0"
|
|
10
10
|
requires-python = ">=3.10,<3.14"
|
|
11
11
|
dependencies = [
|
|
12
|
-
"mtcli>=1.18.1"
|
|
12
|
+
"mtcli>=1.18.1",
|
|
13
|
+
"click (>=8.3.1,<9.0.0)",
|
|
14
|
+
"metatrader5 (>=5.0.5572,<6.0.0)"
|
|
13
15
|
]
|
|
14
16
|
|
|
15
17
|
[project.urls]
|
|
@@ -19,7 +21,7 @@ repository = "https://github.com/vfranca/mtcli-risco"
|
|
|
19
21
|
issues = "https://github.com/vfranca/mtcli-risco/issues"
|
|
20
22
|
|
|
21
23
|
[project.entry-points."mtcli.plugins"]
|
|
22
|
-
|
|
24
|
+
risco = "mtcli_risco.plugin:register"
|
|
23
25
|
|
|
24
26
|
[build-system]
|
|
25
27
|
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
"""Comando monitorar - monitora o prejuízo do dia."""
|
|
2
|
-
|
|
3
|
-
import time
|
|
4
|
-
import click
|
|
5
|
-
from datetime import date
|
|
6
|
-
from mtcli.logger import setup_logger
|
|
7
|
-
from mtcli_risco.conf import LOSS_LIMIT, STATUS_FILE, INTERVALO
|
|
8
|
-
from mtcli_risco.models.checar_model import (
|
|
9
|
-
carregar_estado,
|
|
10
|
-
salvar_estado,
|
|
11
|
-
risco_excedido,
|
|
12
|
-
encerrar_todas_posicoes,
|
|
13
|
-
cancelar_todas_ordens,
|
|
14
|
-
)
|
|
15
|
-
|
|
16
|
-
log = setup_logger()
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
@click.command(
|
|
20
|
-
"monitorar", help="Inicia o monitoramento contínuo do risco diário em tempo real."
|
|
21
|
-
)
|
|
22
|
-
@click.version_option(package_name="mtcli-risco")
|
|
23
|
-
@click.option("--limite", "-l", default=LOSS_LIMIT, help="Limite de perda diária.")
|
|
24
|
-
@click.option(
|
|
25
|
-
"--intervalo",
|
|
26
|
-
"-i",
|
|
27
|
-
default=INTERVALO,
|
|
28
|
-
help="Intervalo entre verificações (segundos), default 60.",
|
|
29
|
-
)
|
|
30
|
-
def monitorar(limite, intervalo):
|
|
31
|
-
"""Monitora continuamente o risco em tempo real."""
|
|
32
|
-
click.echo(f"Monitorando risco a cada {intervalo}s. Limite: {limite}")
|
|
33
|
-
try:
|
|
34
|
-
while True:
|
|
35
|
-
hoje = date.today()
|
|
36
|
-
estado = carregar_estado(STATUS_FILE)
|
|
37
|
-
|
|
38
|
-
if estado.get("data") != hoje.isoformat():
|
|
39
|
-
estado["bloqueado"] = False
|
|
40
|
-
salvar_estado(STATUS_FILE, hoje, False)
|
|
41
|
-
|
|
42
|
-
if not estado.get("bloqueado") and risco_excedido(limite):
|
|
43
|
-
click.echo(f"Limite {limite} excedido. Encerrando posições.")
|
|
44
|
-
log.info(f"Risco excedido em {limite}. Encerrando posições.")
|
|
45
|
-
encerrar_todas_posicoes()
|
|
46
|
-
cancelar_todas_ordens()
|
|
47
|
-
salvar_estado(STATUS_FILE, hoje, True)
|
|
48
|
-
elif estado.get("bloqueado"):
|
|
49
|
-
click.echo(f"O limite {limite} foi excedido. Sistema bloqueado hoje.")
|
|
50
|
-
else:
|
|
51
|
-
click.echo(f"Dentro do limite {limite}")
|
|
52
|
-
|
|
53
|
-
time.sleep(intervalo)
|
|
54
|
-
except KeyboardInterrupt:
|
|
55
|
-
click.echo("Monitoramento interrompido.")
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
if __name__ == "__main__":
|
|
59
|
-
monitorar()
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
"""Comando lucro - exibe os diferentes tipos de lucro."""
|
|
2
|
-
|
|
3
|
-
import click
|
|
4
|
-
from mtcli.logger import setup_logger
|
|
5
|
-
from mtcli_risco.models.trades_model import (
|
|
6
|
-
obter_lucro_aberto,
|
|
7
|
-
calcular_lucro_realizado,
|
|
8
|
-
calcular_lucro_total_dia,
|
|
9
|
-
)
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
log = setup_logger()
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
@click.command(
|
|
16
|
-
"trades", help="Exibe os lucros realizados, abertos e totais do dia atual."
|
|
17
|
-
)
|
|
18
|
-
@click.version_option(package_name="mtcli-risco")
|
|
19
|
-
@click.option(
|
|
20
|
-
"--aberto", "-a", is_flag=True, default=False, help="Exibe o lucro aberto."
|
|
21
|
-
)
|
|
22
|
-
@click.option(
|
|
23
|
-
"--realizado",
|
|
24
|
-
"-r",
|
|
25
|
-
is_flag=True,
|
|
26
|
-
default=False,
|
|
27
|
-
help="Exibe o lucro realizado do dia.",
|
|
28
|
-
)
|
|
29
|
-
@click.option(
|
|
30
|
-
"--total", "-t", is_flag=True, default=False, help="Exibe o lucro total do dia."
|
|
31
|
-
)
|
|
32
|
-
def trades(aberto, realizado, total):
|
|
33
|
-
"""Exibe os lucros aberto, realizado e total do dia."""
|
|
34
|
-
lucro_aberto = obter_lucro_aberto()
|
|
35
|
-
lucro_realizado = calcular_lucro_realizado()
|
|
36
|
-
lucro_total = calcular_lucro_total_dia()
|
|
37
|
-
|
|
38
|
-
if aberto:
|
|
39
|
-
click.echo(f"{lucro_aberto:.2f}")
|
|
40
|
-
return
|
|
41
|
-
|
|
42
|
-
if realizado:
|
|
43
|
-
click.echo(f"{lucro_realizado:.2f}")
|
|
44
|
-
return
|
|
45
|
-
|
|
46
|
-
if total:
|
|
47
|
-
click.echo(f"{lucro_total:.2f}")
|
|
48
|
-
return
|
|
49
|
-
|
|
50
|
-
click.echo(f"lucro em aberto {lucro_aberto:.2f}")
|
|
51
|
-
click.echo(f"lucro realizado {lucro_realizado:.2f}")
|
|
52
|
-
click.echo(f"lucro total {lucro_total:.2f}")
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
if __name__ == "__main__":
|
|
56
|
-
trades()
|
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
"""Verifica dados de risco."""
|
|
2
|
-
|
|
3
|
-
import MetaTrader5 as mt5
|
|
4
|
-
import json
|
|
5
|
-
import os
|
|
6
|
-
from datetime import date, datetime, time
|
|
7
|
-
from mtcli.logger import setup_logger
|
|
8
|
-
from .trades_model import calcular_lucro_total_dia
|
|
9
|
-
from mtcli_risco.mt5_context import mt5_conexao
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
log = setup_logger()
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
def carregar_estado(STATUS_FILE):
|
|
16
|
-
"""Carrega o estado do controle de risco."""
|
|
17
|
-
if os.path.exists(STATUS_FILE):
|
|
18
|
-
with open(STATUS_FILE, "r") as f:
|
|
19
|
-
log.info(f"Carregando dados do arquivo {STATUS_FILE}")
|
|
20
|
-
return json.load(f)
|
|
21
|
-
return {"data": None, "bloqueado": False}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
def salvar_estado(STATUS_FILE, data, bloqueado):
|
|
25
|
-
"""Salva o estado do controle de risco."""
|
|
26
|
-
with open(STATUS_FILE, "w") as f:
|
|
27
|
-
json.dump({"data": data.isoformat(), "bloqueado": bloqueado}, f)
|
|
28
|
-
log.info(f"Salvando o estado: data {data} bloqueado {bloqueado}")
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
def encerrar_todas_posicoes():
|
|
32
|
-
"""Encerra todas as posições abertas."""
|
|
33
|
-
with mt5_conexao():
|
|
34
|
-
positions = mt5.positions_get()
|
|
35
|
-
if not positions:
|
|
36
|
-
log.info("Nenhuma posição aberta para fechar.")
|
|
37
|
-
return
|
|
38
|
-
|
|
39
|
-
with mt5_conexao():
|
|
40
|
-
for pos in positions:
|
|
41
|
-
tipo_oposto = (
|
|
42
|
-
mt5.ORDER_TYPE_SELL
|
|
43
|
-
if pos.type == mt5.ORDER_TYPE_BUY
|
|
44
|
-
else mt5.ORDER_TYPE_BUY
|
|
45
|
-
)
|
|
46
|
-
ordem_fechar = {
|
|
47
|
-
"action": mt5.TRADE_ACTION_DEAL,
|
|
48
|
-
"symbol": pos.symbol,
|
|
49
|
-
"volume": pos.volume,
|
|
50
|
-
"type": tipo_oposto,
|
|
51
|
-
"position": pos.ticket,
|
|
52
|
-
"deviation": 10,
|
|
53
|
-
"magic": 1000,
|
|
54
|
-
"comment": "Fechando posição por limite de risco",
|
|
55
|
-
}
|
|
56
|
-
log.info(
|
|
57
|
-
f"Requizição para encerramento de posições pelo risco: {ordem_fechar}"
|
|
58
|
-
)
|
|
59
|
-
resultado = mt5.order_send(ordem_fechar)
|
|
60
|
-
|
|
61
|
-
if resultado is None:
|
|
62
|
-
log.error("Erro ao enviar ordem: resultado é None.")
|
|
63
|
-
continue
|
|
64
|
-
|
|
65
|
-
if resultado.retcode != mt5.TRADE_RETCODE_DONE:
|
|
66
|
-
log.error(f"Falha ao fechar posição {pos.ticket}: {resultado.retcode}")
|
|
67
|
-
else:
|
|
68
|
-
log.info(f"Posição {pos.ticket} fechada com sucesso.")
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
def cancelar_todas_ordens():
|
|
72
|
-
"""Cancela todas órdens pendentes."""
|
|
73
|
-
with mt5_conexao():
|
|
74
|
-
ordens = mt5.orders_get()
|
|
75
|
-
if not ordens:
|
|
76
|
-
log.info("Nenhuma ordem pendente para cancelar.")
|
|
77
|
-
return
|
|
78
|
-
|
|
79
|
-
with mt5_conexao():
|
|
80
|
-
for ordem in ordens:
|
|
81
|
-
resultado = mt5.order_delete(ordem.ticket)
|
|
82
|
-
if resultado.retcode != mt5.TRADE_RETCODE_DONE:
|
|
83
|
-
log.error(
|
|
84
|
-
f"Falha ao cancelar ordem {ordem.ticket}: {resultado.retcode}"
|
|
85
|
-
)
|
|
86
|
-
else:
|
|
87
|
-
log.info(f"Ordem {ordem.ticket} cancelada com sucesso.")
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
def risco_excedido(limite):
|
|
91
|
-
"""Verifica se o loss limit do dia foi atingido."""
|
|
92
|
-
try:
|
|
93
|
-
total_lucro = calcular_lucro_total_dia()
|
|
94
|
-
if total_lucro <= limite:
|
|
95
|
-
log.info(
|
|
96
|
-
f"Limite de prejuízo excedido! prejuízo: {total_lucro:.2f}, limite: {limite:.2f}"
|
|
97
|
-
)
|
|
98
|
-
return True
|
|
99
|
-
return False
|
|
100
|
-
except Exception as e:
|
|
101
|
-
log.error(f"Erro ao verificar risco: {e}")
|
|
102
|
-
return False
|
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
"""Cálculos do lucro do dia."""
|
|
2
|
-
|
|
3
|
-
import MetaTrader5 as mt5
|
|
4
|
-
from datetime import date, datetime, time
|
|
5
|
-
from mtcli.conecta import conectar, shutdown
|
|
6
|
-
from mtcli.logger import setup_logger
|
|
7
|
-
from mtcli_risco.mt5_context import mt5_conexao
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
log = setup_logger()
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def contar_transacoes_realizadas() -> int:
|
|
14
|
-
"""Conta a quantidade de posições encerradas no dia (transações de fechamento)."""
|
|
15
|
-
hoje = datetime.now().date()
|
|
16
|
-
inicio = datetime.combine(hoje, time(0, 0))
|
|
17
|
-
fim = datetime.combine(hoje, time(23, 59))
|
|
18
|
-
|
|
19
|
-
with mt5_conexao():
|
|
20
|
-
deals = mt5.history_deals_get(inicio, fim)
|
|
21
|
-
|
|
22
|
-
if deals is None:
|
|
23
|
-
log.warning("Nenhum deal retornado.")
|
|
24
|
-
return 0
|
|
25
|
-
|
|
26
|
-
if not isinstance(deals, (list, tuple)):
|
|
27
|
-
deals = [deals]
|
|
28
|
-
|
|
29
|
-
# Types 1 = buy, 2 = sell → usados para fechar posições
|
|
30
|
-
transacoes = [d for d in deals if d.type in (1, 2)]
|
|
31
|
-
|
|
32
|
-
log.info(f"Transações realizadas hoje: {len(transacoes)}")
|
|
33
|
-
return len(transacoes)
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
def calcular_lucro_realizado() -> float:
|
|
37
|
-
"""Calcula o lucro realizado do dia."""
|
|
38
|
-
hoje = datetime.now().date()
|
|
39
|
-
inicio = datetime.combine(hoje, time(0, 0))
|
|
40
|
-
fim = datetime.combine(hoje, time(23, 59))
|
|
41
|
-
|
|
42
|
-
with mt5_conexao():
|
|
43
|
-
deals = mt5.history_deals_get(inicio, fim)
|
|
44
|
-
log.info(f"Deals recebidos: {len(deals) if deals else 0}")
|
|
45
|
-
|
|
46
|
-
if deals is None or len(deals) == 0:
|
|
47
|
-
log.warning("Nenhum deal retornado.")
|
|
48
|
-
return 0.0
|
|
49
|
-
|
|
50
|
-
lucro_realizado = sum(
|
|
51
|
-
deal.profit for deal in deals if deal.entry == mt5.DEAL_ENTRY_OUT
|
|
52
|
-
)
|
|
53
|
-
|
|
54
|
-
log.info(f"Lucro realizado do dia: {lucro_realizado:.2f}")
|
|
55
|
-
return lucro_realizado
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
def obter_lucro_aberto() -> float:
|
|
59
|
-
"""Obtem o lucro em aberto."""
|
|
60
|
-
with mt5_conexao():
|
|
61
|
-
info = mt5.account_info()
|
|
62
|
-
|
|
63
|
-
lucro_aberto = info.profit if info else 0.0
|
|
64
|
-
log.info(f"lucro aberto: {lucro_aberto:.2f}")
|
|
65
|
-
|
|
66
|
-
return lucro_aberto
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
def calcular_lucro_total_dia() -> float:
|
|
70
|
-
"""Calcula o lucro total do dia."""
|
|
71
|
-
realizado = calcular_lucro_realizado()
|
|
72
|
-
aberto = obter_lucro_aberto()
|
|
73
|
-
total = realizado + aberto
|
|
74
|
-
log.info(
|
|
75
|
-
f"Lucro realizado: {realizado:.2f}, lucro aberto: {aberto:.2f}, total: {total:.2f}"
|
|
76
|
-
)
|
|
77
|
-
return total
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
"""Registra os comandos do plugin."""
|
|
2
|
-
|
|
3
|
-
from .commands.checar import checar
|
|
4
|
-
from .commands.monitorar import monitorar
|
|
5
|
-
from .commands.trades import trades
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
def register(cli):
|
|
9
|
-
cli.add_command(checar, name="checar")
|
|
10
|
-
cli.add_command(monitorar, name="monitorar")
|
|
11
|
-
cli.add_command(trades, name="trades")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|