mtcli-risco 2.3.0.dev0__tar.gz → 2.3.0.dev1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/PKG-INFO +1 -1
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/mtcli_risco/cli.py +10 -4
- mtcli_risco-2.3.0.dev1/mtcli_risco/commands/monitorar.py +64 -0
- mtcli_risco-2.3.0.dev1/mtcli_risco/commands/panic.py +36 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/mtcli_risco/models/checar_model.py +1 -1
- mtcli_risco-2.3.0.dev1/mtcli_risco/models/panic_model.py +170 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/mtcli_risco/models/trades_model.py +1 -1
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/mtcli_risco/plugin.py +2 -2
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/pyproject.toml +1 -1
- mtcli_risco-2.3.0.dev0/mtcli_risco/commands/monitorar.py +0 -63
- mtcli_risco-2.3.0.dev0/mtcli_risco/mt5_context.py +0 -11
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/LICENSE +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/README.md +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/mtcli_risco/__init__.py +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/mtcli_risco/commands/__init__.py +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/mtcli_risco/commands/checar.py +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/mtcli_risco/commands/trades.py +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/mtcli_risco/conf.py +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev1}/mtcli_risco/models/__init__.py +0 -0
|
@@ -1,12 +1,17 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Comando principal e registro dos subcomandos
|
|
3
|
+
"""
|
|
4
|
+
|
|
1
5
|
import click
|
|
2
6
|
from .commands.checar import checar_cmd
|
|
3
7
|
from .commands.monitorar import monitorar_cmd
|
|
4
8
|
from .commands.trades import trades_cmd
|
|
9
|
+
from .commands.panic import panic_cmd
|
|
5
10
|
|
|
6
11
|
|
|
7
12
|
@click.group()
|
|
8
13
|
@click.version_option(package_name="mtcli-risco")
|
|
9
|
-
def
|
|
14
|
+
def cli():
|
|
10
15
|
"""
|
|
11
16
|
Plugin mtcli-risco.
|
|
12
17
|
|
|
@@ -16,6 +21,7 @@ def risco_cli():
|
|
|
16
21
|
pass
|
|
17
22
|
|
|
18
23
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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")
|
|
@@ -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}")
|
|
@@ -13,7 +13,7 @@ import os
|
|
|
13
13
|
from datetime import date
|
|
14
14
|
import MetaTrader5 as mt5
|
|
15
15
|
from mtcli.logger import setup_logger
|
|
16
|
-
from
|
|
16
|
+
from mtcli.mt5_context import mt5_conexao
|
|
17
17
|
from .trades_model import calcular_lucro_total_dia
|
|
18
18
|
|
|
19
19
|
log = setup_logger()
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Modo PANIC CLOSE.
|
|
3
|
+
|
|
4
|
+
- Funciona em conta hedge e netting
|
|
5
|
+
- Detecta market fechado
|
|
6
|
+
- Reexecuta automaticamente quando o market abrir
|
|
7
|
+
- Suporta modo DRY-RUN (simulação)
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import time
|
|
11
|
+
import MetaTrader5 as mt5
|
|
12
|
+
from mtcli.logger import setup_logger
|
|
13
|
+
from mtcli.mt5_context import mt5_conexao
|
|
14
|
+
|
|
15
|
+
log = setup_logger()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _trade_permitido() -> bool:
|
|
19
|
+
info = mt5.account_info()
|
|
20
|
+
return bool(info and info.trade_allowed)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _market_aberto(symbol: str) -> bool:
|
|
24
|
+
info = mt5.symbol_info(symbol)
|
|
25
|
+
return bool(info and info.trade_mode == mt5.SYMBOL_TRADE_MODE_FULL)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _close_position(position, dry_run: bool = False) -> bool:
|
|
29
|
+
symbol = position.symbol
|
|
30
|
+
tick = mt5.symbol_info_tick(symbol)
|
|
31
|
+
|
|
32
|
+
if not tick:
|
|
33
|
+
log.error(f"[PANIC] Tick indisponível para {symbol}")
|
|
34
|
+
return False
|
|
35
|
+
|
|
36
|
+
tipo = (
|
|
37
|
+
mt5.ORDER_TYPE_SELL
|
|
38
|
+
if position.type == mt5.ORDER_TYPE_BUY
|
|
39
|
+
else mt5.ORDER_TYPE_BUY
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
price = tick.bid if tipo == mt5.ORDER_TYPE_SELL else tick.ask
|
|
43
|
+
|
|
44
|
+
request = {
|
|
45
|
+
"action": mt5.TRADE_ACTION_DEAL,
|
|
46
|
+
"symbol": symbol,
|
|
47
|
+
"volume": position.volume,
|
|
48
|
+
"type": tipo,
|
|
49
|
+
"price": price,
|
|
50
|
+
"deviation": 20,
|
|
51
|
+
"magic": 999999,
|
|
52
|
+
"comment": "PANIC CLOSE",
|
|
53
|
+
"type_time": mt5.ORDER_TIME_GTC,
|
|
54
|
+
"type_filling": mt5.ORDER_FILLING_IOC,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if position.ticket:
|
|
58
|
+
request["position"] = position.ticket
|
|
59
|
+
|
|
60
|
+
if dry_run:
|
|
61
|
+
log.warning(f"[PANIC][DRY] Fechamento simulado: {request}")
|
|
62
|
+
return True
|
|
63
|
+
|
|
64
|
+
result = mt5.order_send(request)
|
|
65
|
+
|
|
66
|
+
if not result:
|
|
67
|
+
log.error(
|
|
68
|
+
f"[PANIC] order_send None | {symbol} | last_error={mt5.last_error()}"
|
|
69
|
+
)
|
|
70
|
+
return False
|
|
71
|
+
|
|
72
|
+
if result.retcode != mt5.TRADE_RETCODE_DONE:
|
|
73
|
+
log.error(
|
|
74
|
+
f"[PANIC] Falha ao fechar {symbol} | retcode={result.retcode}"
|
|
75
|
+
)
|
|
76
|
+
return False
|
|
77
|
+
|
|
78
|
+
log.critical(
|
|
79
|
+
f"[PANIC] Posição fechada | {symbol} vol={position.volume}"
|
|
80
|
+
)
|
|
81
|
+
return True
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def panic_close_all(
|
|
85
|
+
retry_on_market_open: bool = True,
|
|
86
|
+
retry_interval: int = 60,
|
|
87
|
+
dry_run: bool = False,
|
|
88
|
+
) -> dict:
|
|
89
|
+
"""
|
|
90
|
+
Executa o fechamento emergencial de posições e ordens.
|
|
91
|
+
|
|
92
|
+
retry_on_market_open:
|
|
93
|
+
Reexecuta automaticamente quando o market abrir.
|
|
94
|
+
|
|
95
|
+
dry_run:
|
|
96
|
+
Simula ações sem enviar ordens.
|
|
97
|
+
"""
|
|
98
|
+
stats = {
|
|
99
|
+
"positions_total": 0,
|
|
100
|
+
"positions_closed": 0,
|
|
101
|
+
"orders_cancelled": 0,
|
|
102
|
+
"market_closed": False,
|
|
103
|
+
"trade_disabled": False,
|
|
104
|
+
"dry_run": dry_run,
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
while True:
|
|
108
|
+
with mt5_conexao():
|
|
109
|
+
if not _trade_permitido():
|
|
110
|
+
log.critical("[PANIC] Trading desabilitado na conta!")
|
|
111
|
+
stats["trade_disabled"] = True
|
|
112
|
+
return stats
|
|
113
|
+
|
|
114
|
+
positions = mt5.positions_get()
|
|
115
|
+
orders = mt5.orders_get()
|
|
116
|
+
|
|
117
|
+
if positions:
|
|
118
|
+
stats["positions_total"] = len(positions)
|
|
119
|
+
|
|
120
|
+
market_fechado = False
|
|
121
|
+
|
|
122
|
+
# 1️⃣ Fechar posições
|
|
123
|
+
if positions:
|
|
124
|
+
for pos in positions:
|
|
125
|
+
if not _market_aberto(pos.symbol):
|
|
126
|
+
market_fechado = True
|
|
127
|
+
log.critical(
|
|
128
|
+
f"[PANIC] Market fechado para {pos.symbol}"
|
|
129
|
+
)
|
|
130
|
+
continue
|
|
131
|
+
|
|
132
|
+
if _close_position(pos, dry_run=dry_run):
|
|
133
|
+
stats["positions_closed"] += 1
|
|
134
|
+
|
|
135
|
+
# 2️⃣ Cancelar ordens pendentes
|
|
136
|
+
if orders:
|
|
137
|
+
for ordem in orders:
|
|
138
|
+
if dry_run:
|
|
139
|
+
log.warning(
|
|
140
|
+
f"[PANIC][DRY] Cancelamento simulado | ticket={ordem.ticket}"
|
|
141
|
+
)
|
|
142
|
+
stats["orders_cancelled"] += 1
|
|
143
|
+
continue
|
|
144
|
+
|
|
145
|
+
result = mt5.order_delete(ordem.ticket)
|
|
146
|
+
if result and result.retcode == mt5.TRADE_RETCODE_DONE:
|
|
147
|
+
stats["orders_cancelled"] += 1
|
|
148
|
+
log.warning(
|
|
149
|
+
f"[PANIC] Ordem cancelada | ticket={ordem.ticket}"
|
|
150
|
+
)
|
|
151
|
+
else:
|
|
152
|
+
log.error(
|
|
153
|
+
f"[PANIC] Falha ao cancelar ordem {ordem.ticket}"
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
if not market_fechado:
|
|
157
|
+
break
|
|
158
|
+
|
|
159
|
+
stats["market_closed"] = True
|
|
160
|
+
|
|
161
|
+
if not retry_on_market_open:
|
|
162
|
+
break
|
|
163
|
+
|
|
164
|
+
log.critical(
|
|
165
|
+
f"[PANIC] Market fechado. Repetindo em {retry_interval}s..."
|
|
166
|
+
)
|
|
167
|
+
time.sleep(retry_interval)
|
|
168
|
+
|
|
169
|
+
log.critical(f"[PANIC] Resultado final: {stats}")
|
|
170
|
+
return stats
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
Registro do plugin mtcli-risco no mtcli principal.
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
|
-
from .cli import
|
|
5
|
+
from .cli import cli as risco
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
def register(main_cli):
|
|
9
9
|
"""
|
|
10
10
|
Registra o grupo de comandos 'risco' no mtcli principal.
|
|
11
11
|
"""
|
|
12
|
-
main_cli.add_command(
|
|
12
|
+
main_cli.add_command(risco, name="risco")
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Comando monitorar.
|
|
3
|
-
|
|
4
|
-
Monitora continuamente o risco diário em intervalos regulares.
|
|
5
|
-
"""
|
|
6
|
-
|
|
7
|
-
import time
|
|
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, INTERVALO
|
|
12
|
-
from mtcli_risco.models.checar_model import (
|
|
13
|
-
carregar_estado,
|
|
14
|
-
salvar_estado,
|
|
15
|
-
risco_excedido,
|
|
16
|
-
encerrar_todas_posicoes,
|
|
17
|
-
cancelar_todas_ordens,
|
|
18
|
-
)
|
|
19
|
-
|
|
20
|
-
log = setup_logger()
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
@click.command(
|
|
24
|
-
"monitorar",
|
|
25
|
-
help="Monitora continuamente o risco diário em tempo real.",
|
|
26
|
-
)
|
|
27
|
-
@click.version_option(package_name="mtcli-risco")
|
|
28
|
-
@click.option("--limite", "-l", default=LOSS_LIMIT, help="Limite de perda diária.")
|
|
29
|
-
@click.option(
|
|
30
|
-
"--intervalo",
|
|
31
|
-
"-i",
|
|
32
|
-
default=INTERVALO,
|
|
33
|
-
help="Intervalo entre verificações (segundos).",
|
|
34
|
-
)
|
|
35
|
-
def monitorar_cmd(limite: float, intervalo: int):
|
|
36
|
-
"""
|
|
37
|
-
Inicia o monitoramento contínuo do risco diário.
|
|
38
|
-
"""
|
|
39
|
-
click.echo(f"Monitorando risco a cada {intervalo}s | Limite: {limite:.2f}")
|
|
40
|
-
log.info(f"[MONITOR] Iniciado | limite={limite} intervalo={intervalo}s")
|
|
41
|
-
|
|
42
|
-
try:
|
|
43
|
-
while True:
|
|
44
|
-
hoje = date.today()
|
|
45
|
-
estado = carregar_estado(STATUS_FILE)
|
|
46
|
-
|
|
47
|
-
if estado["data"] != hoje.isoformat():
|
|
48
|
-
log.info("[ESTADO] Novo dia detectado, resetando bloqueio.")
|
|
49
|
-
salvar_estado(STATUS_FILE, hoje, False)
|
|
50
|
-
estado["bloqueado"] = False
|
|
51
|
-
|
|
52
|
-
if not estado["bloqueado"] and risco_excedido(limite):
|
|
53
|
-
click.echo(f"Limite {limite:.2f} excedido. Encerrando posições.")
|
|
54
|
-
log.warning("[RISCO] Limite excedido durante monitoramento.")
|
|
55
|
-
encerrar_todas_posicoes()
|
|
56
|
-
cancelar_todas_ordens()
|
|
57
|
-
salvar_estado(STATUS_FILE, hoje, True)
|
|
58
|
-
|
|
59
|
-
time.sleep(intervalo)
|
|
60
|
-
|
|
61
|
-
except KeyboardInterrupt:
|
|
62
|
-
click.echo("Monitoramento interrompido.")
|
|
63
|
-
log.info("[MONITOR] Interrompido pelo usuário.")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|