mtcli-risco 2.3.0.dev0__tar.gz → 2.3.0.dev2__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.dev2}/PKG-INFO +1 -1
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev2}/mtcli_risco/cli.py +10 -4
- mtcli_risco-2.3.0.dev2/mtcli_risco/commands/monitorar.py +64 -0
- mtcli_risco-2.3.0.dev2/mtcli_risco/commands/panic.py +36 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev2}/mtcli_risco/models/checar_model.py +1 -1
- mtcli_risco-2.3.0.dev2/mtcli_risco/models/panic_model.py +206 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev2}/mtcli_risco/models/trades_model.py +1 -1
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev2}/mtcli_risco/plugin.py +2 -2
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev2}/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.dev2}/LICENSE +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev2}/README.md +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev2}/mtcli_risco/__init__.py +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev2}/mtcli_risco/commands/__init__.py +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev2}/mtcli_risco/commands/checar.py +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev2}/mtcli_risco/commands/trades.py +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev2}/mtcli_risco/conf.py +0 -0
- {mtcli_risco-2.3.0.dev0 → mtcli_risco-2.3.0.dev2}/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,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
|
|
@@ -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
|