mtcli-risco 2.4.0__tar.gz → 2.4.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mtcli-risco
3
- Version: 2.4.0
3
+ Version: 2.4.1
4
4
  Summary: Plugin mtcli para controle de loss diário
5
5
  License-Expression: GPL-3.0
6
6
  License-File: LICENSE
@@ -0,0 +1,45 @@
1
+ """
2
+ Comando PANIC CLOSE.
3
+ """
4
+
5
+ import click
6
+ from mtcli.logger import setup_logger
7
+ from mtcli_risco.models.panic_model import panic_close_all
8
+ from mtcli_risco import conf
9
+
10
+ log = setup_logger()
11
+
12
+
13
+ @click.command()
14
+ @click.option(
15
+ "--no-retry",
16
+ is_flag=True,
17
+ help="Não aguardar reabertura do mercado",
18
+ )
19
+ @click.option(
20
+ "--dry-run",
21
+ is_flag=True,
22
+ help="Simula o panic close sem enviar ordens nem hardstop",
23
+ )
24
+ @click.option(
25
+ "--terminal-path",
26
+ type=click.Path(exists=True),
27
+ help="Caminho do terminal MT5 (override temporário)",
28
+ )
29
+ def panic_cmd(no_retry: bool, dry_run: bool, terminal_path: str | None):
30
+ """
31
+ Executa o PANIC CLOSE com HARDSTOP.
32
+ """
33
+ if terminal_path:
34
+ log.warning(
35
+ f"[PANIC] Override do caminho do terminal: {terminal_path}"
36
+ )
37
+ conf.MT5_TERMINAL_PATH = terminal_path
38
+
39
+ resultado = panic_close_all(
40
+ retry_on_market_open=not no_retry,
41
+ dry_run=dry_run,
42
+ )
43
+
44
+ click.echo("PANIC CLOSE executado.")
45
+ click.echo(resultado)
@@ -0,0 +1,31 @@
1
+ import os
2
+ from mtcli.conf import config
3
+
4
+
5
+ LOSS_LIMIT = float(
6
+ os.getenv(
7
+ "LOSS_LIMIT",
8
+ config["DEFAULT"].getfloat("loss_limit", fallback=-180.00),
9
+ )
10
+ )
11
+
12
+ STATUS_FILE = os.getenv(
13
+ "STATUS_FILE",
14
+ config["DEFAULT"].get("status_file", fallback="bloqueio.json"),
15
+ )
16
+
17
+ INTERVALO = int(
18
+ os.getenv(
19
+ "INTERVALO",
20
+ config["DEFAULT"].getint("intervalo", fallback=60),
21
+ )
22
+ )
23
+
24
+ # Caminho do executável do MetaTrader 5 (usado no HARDSTOP)
25
+ MT5_TERMINAL_PATH = os.getenv(
26
+ "MT5_TERMINAL_PATH",
27
+ config["DEFAULT"].get(
28
+ "mt5_terminal_path",
29
+ fallback=r"C:\Program Files\MetaTrader 5\terminal64.exe",
30
+ ),
31
+ )
@@ -9,12 +9,11 @@ Responsável por:
9
9
 
10
10
  import os
11
11
  import subprocess
12
- import signal
13
12
  from mtcli.logger import setup_logger
13
+ from mtcli_risco.conf import MT5_TERMINAL_PATH
14
14
 
15
15
  log = setup_logger()
16
16
 
17
- MT5_PROCESS_NAME = "terminal64.exe"
18
17
  FIREWALL_RULE_NAME = "MT5_HARDSTOP_BLOCK"
19
18
 
20
19
 
@@ -40,14 +39,16 @@ def kill_mt5_process() -> None:
40
39
  """
41
40
  Encerra o processo do MetaTrader 5 à força.
42
41
  """
43
- log.critical("[HARDSTOP] Encerrando processo do MT5")
42
+ exe_name = os.path.basename(MT5_TERMINAL_PATH)
43
+
44
+ log.critical(f"[HARDSTOP] Encerrando processo {exe_name}")
44
45
 
45
46
  _run(
46
47
  [
47
48
  "taskkill",
48
- "/F", # força
49
+ "/F",
49
50
  "/IM",
50
- MT5_PROCESS_NAME,
51
+ exe_name,
51
52
  ]
52
53
  )
53
54
 
@@ -56,9 +57,11 @@ def block_mt5_firewall() -> None:
56
57
  """
57
58
  Bloqueia qualquer tráfego de rede do MT5 via Firewall do Windows.
58
59
  """
59
- log.critical("[HARDSTOP] Bloqueando tráfego de rede do MT5 (Firewall)")
60
+ log.critical(
61
+ f"[HARDSTOP] Bloqueando tráfego de rede do MT5 | {MT5_TERMINAL_PATH}"
62
+ )
60
63
 
61
- # Remove regra anterior se existir (idempotente)
64
+ # Remove regra anterior (idempotente)
62
65
  _run(
63
66
  [
64
67
  "netsh",
@@ -81,7 +84,7 @@ def block_mt5_firewall() -> None:
81
84
  f"name={FIREWALL_RULE_NAME}",
82
85
  "dir=out",
83
86
  "action=block",
84
- f"program=%ProgramFiles%\\MetaTrader 5\\terminal64.exe",
87
+ f"program={MT5_TERMINAL_PATH}",
85
88
  "enable=yes",
86
89
  ]
87
90
  )
@@ -1,217 +1,217 @@
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
- - Acionar HARDSTOP via Sistema Operacional (Windows)
10
- """
11
-
12
- import time
13
- import MetaTrader5 as mt5
14
-
15
- from mtcli.logger import setup_logger
16
- from mtcli.mt5_context import mt5_conexao
17
- from mtcli_risco.models.hardstop_model import hardstop
18
-
19
- log = setup_logger()
20
-
21
-
22
- def _trade_permitido() -> bool:
23
- """
24
- Verifica se a conta permite trading.
25
- """
26
- info = mt5.account_info()
27
- return bool(info and info.trade_allowed)
28
-
29
-
30
- def _market_aberto(symbol: str) -> bool:
31
- """
32
- Verifica se o mercado do símbolo está aberto para trading.
33
- """
34
- info = mt5.symbol_info(symbol)
35
- return bool(info and info.trade_mode == mt5.SYMBOL_TRADE_MODE_FULL)
36
-
37
-
38
- def _close_position(position, dry_run: bool = False) -> bool:
39
- """
40
- Fecha uma posição individual (compatível com hedge e netting).
41
- """
42
- symbol = position.symbol
43
- tick = mt5.symbol_info_tick(symbol)
44
-
45
- if not tick:
46
- log.error(f"[PANIC] Tick indisponível para {symbol}")
47
- return False
48
-
49
- order_type = (
50
- mt5.ORDER_TYPE_SELL
51
- if position.type == mt5.ORDER_TYPE_BUY
52
- else mt5.ORDER_TYPE_BUY
53
- )
54
-
55
- price = tick.bid if order_type == mt5.ORDER_TYPE_SELL else tick.ask
56
-
57
- request = {
58
- "action": mt5.TRADE_ACTION_DEAL,
59
- "symbol": symbol,
60
- "volume": position.volume,
61
- "type": order_type,
62
- "price": price,
63
- "deviation": 20,
64
- "magic": 999999,
65
- "comment": "PANIC CLOSE",
66
- "type_time": mt5.ORDER_TIME_GTC,
67
- "type_filling": mt5.ORDER_FILLING_IOC,
68
- }
69
-
70
- # Conta hedge → fechamento por ticket
71
- if position.ticket:
72
- request["position"] = position.ticket
73
-
74
- if dry_run:
75
- log.warning(f"[PANIC][DRY] Fechamento simulado: {request}")
76
- return True
77
-
78
- result = mt5.order_send(request)
79
-
80
- if not result:
81
- log.error(
82
- f"[PANIC] order_send retornou None | "
83
- f"{symbol} | last_error={mt5.last_error()}"
84
- )
85
- return False
86
-
87
- if result.retcode != mt5.TRADE_RETCODE_DONE:
88
- log.error(
89
- f"[PANIC] Falha ao fechar posição {symbol} | "
90
- f"retcode={result.retcode}"
91
- )
92
- return False
93
-
94
- log.critical(
95
- f"[PANIC] Posição fechada | {symbol} vol={position.volume}"
96
- )
97
- return True
98
-
99
-
100
- def panic_close_all(
101
- retry_on_market_open: bool = True,
102
- retry_interval: int = 60,
103
- dry_run: bool = False,
104
- ) -> dict:
105
- """
106
- Executa o fechamento emergencial de TODAS as posições e ordens.
107
-
108
- Parâmetros
109
- ----------
110
- retry_on_market_open : bool
111
- Reexecuta automaticamente quando o market estiver fechado.
112
- retry_interval : int
113
- Intervalo (segundos) entre tentativas quando market fechado.
114
- dry_run : bool
115
- Simula as ações sem enviar ordens reais.
116
-
117
- Retorna
118
- -------
119
- dict
120
- Estatísticas da execução do panic close.
121
- """
122
- stats = {
123
- "positions_total": 0,
124
- "positions_closed": 0,
125
- "orders_cancelled": 0,
126
- "market_closed": False,
127
- "trade_disabled": False,
128
- "dry_run": dry_run,
129
- "hardstop_executed": False,
130
- }
131
-
132
- while True:
133
- market_fechado = False
134
-
135
- with mt5_conexao():
136
- if not _trade_permitido():
137
- log.critical("[PANIC] Trading desabilitado na conta!")
138
- stats["trade_disabled"] = True
139
- break
140
-
141
- positions = mt5.positions_get()
142
- orders = mt5.orders_get()
143
-
144
- if positions:
145
- stats["positions_total"] = len(positions)
146
-
147
- # 1️⃣ Fechamento de posições
148
- if positions:
149
- for pos in positions:
150
- if not _market_aberto(pos.symbol):
151
- market_fechado = True
152
- log.critical(
153
- f"[PANIC] Market fechado para {pos.symbol}"
154
- )
155
- continue
156
-
157
- if _close_position(pos, dry_run=dry_run):
158
- stats["positions_closed"] += 1
159
-
160
- # 2️⃣ Cancelamento de ordens pendentes
161
- if orders:
162
- for ordem in orders:
163
- if dry_run:
164
- log.warning(
165
- f"[PANIC][DRY] Cancelamento simulado | "
166
- f"ticket={ordem.ticket}"
167
- )
168
- stats["orders_cancelled"] += 1
169
- continue
170
-
171
- request = {
172
- "action": mt5.TRADE_ACTION_REMOVE,
173
- "order": ordem.ticket,
174
- }
175
-
176
- result = mt5.order_send(request)
177
-
178
- if not result:
179
- log.error(
180
- f"[PANIC] Falha ao cancelar ordem {ordem.ticket} | "
181
- f"last_error={mt5.last_error()}"
182
- )
183
- continue
184
-
185
- if result.retcode == mt5.TRADE_RETCODE_DONE:
186
- stats["orders_cancelled"] += 1
187
- log.warning(
188
- f"[PANIC] Ordem cancelada | ticket={ordem.ticket}"
189
- )
190
- else:
191
- log.error(
192
- f"[PANIC] Falha ao cancelar ordem {ordem.ticket} | "
193
- f"retcode={result.retcode}"
194
- )
195
-
196
- if not market_fechado:
197
- break
198
-
199
- stats["market_closed"] = True
200
-
201
- if not retry_on_market_open:
202
- break
203
-
204
- log.critical(
205
- f"[PANIC] Market fechado. Nova tentativa em {retry_interval}s..."
206
- )
207
- time.sleep(retry_interval)
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
-
216
- log.critical(f"[PANIC] Resultado final: {stats}")
217
- return stats
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
+ - Acionar HARDSTOP via Sistema Operacional (Windows)
10
+ """
11
+
12
+ import time
13
+ import MetaTrader5 as mt5
14
+
15
+ from mtcli.logger import setup_logger
16
+ from mtcli.mt5_context import mt5_conexao
17
+ from mtcli_risco.models.hardstop_model import hardstop
18
+
19
+ log = setup_logger()
20
+
21
+
22
+ def _trade_permitido() -> bool:
23
+ """
24
+ Verifica se a conta permite trading.
25
+ """
26
+ info = mt5.account_info()
27
+ return bool(info and info.trade_allowed)
28
+
29
+
30
+ def _market_aberto(symbol: str) -> bool:
31
+ """
32
+ Verifica se o mercado do símbolo está aberto para trading.
33
+ """
34
+ info = mt5.symbol_info(symbol)
35
+ return bool(info and info.trade_mode == mt5.SYMBOL_TRADE_MODE_FULL)
36
+
37
+
38
+ def _close_position(position, dry_run: bool = False) -> bool:
39
+ """
40
+ Fecha uma posição individual (compatível com hedge e netting).
41
+ """
42
+ symbol = position.symbol
43
+ tick = mt5.symbol_info_tick(symbol)
44
+
45
+ if not tick:
46
+ log.error(f"[PANIC] Tick indisponível para {symbol}")
47
+ return False
48
+
49
+ order_type = (
50
+ mt5.ORDER_TYPE_SELL
51
+ if position.type == mt5.ORDER_TYPE_BUY
52
+ else mt5.ORDER_TYPE_BUY
53
+ )
54
+
55
+ price = tick.bid if order_type == mt5.ORDER_TYPE_SELL else tick.ask
56
+
57
+ request = {
58
+ "action": mt5.TRADE_ACTION_DEAL,
59
+ "symbol": symbol,
60
+ "volume": position.volume,
61
+ "type": order_type,
62
+ "price": price,
63
+ "deviation": 20,
64
+ "magic": 999999,
65
+ "comment": "PANIC CLOSE",
66
+ "type_time": mt5.ORDER_TIME_GTC,
67
+ "type_filling": mt5.ORDER_FILLING_IOC,
68
+ }
69
+
70
+ # Conta hedge → fechamento por ticket
71
+ if position.ticket:
72
+ request["position"] = position.ticket
73
+
74
+ if dry_run:
75
+ log.warning(f"[PANIC][DRY] Fechamento simulado: {request}")
76
+ return True
77
+
78
+ result = mt5.order_send(request)
79
+
80
+ if not result:
81
+ log.error(
82
+ f"[PANIC] order_send retornou None | "
83
+ f"{symbol} | last_error={mt5.last_error()}"
84
+ )
85
+ return False
86
+
87
+ if result.retcode != mt5.TRADE_RETCODE_DONE:
88
+ log.error(
89
+ f"[PANIC] Falha ao fechar posição {symbol} | "
90
+ f"retcode={result.retcode}"
91
+ )
92
+ return False
93
+
94
+ log.critical(
95
+ f"[PANIC] Posição fechada | {symbol} vol={position.volume}"
96
+ )
97
+ return True
98
+
99
+
100
+ def panic_close_all(
101
+ retry_on_market_open: bool = True,
102
+ retry_interval: int = 60,
103
+ dry_run: bool = False,
104
+ ) -> dict:
105
+ """
106
+ Executa o fechamento emergencial de TODAS as posições e ordens.
107
+
108
+ Parâmetros
109
+ ----------
110
+ retry_on_market_open : bool
111
+ Reexecuta automaticamente quando o market estiver fechado.
112
+ retry_interval : int
113
+ Intervalo (segundos) entre tentativas quando market fechado.
114
+ dry_run : bool
115
+ Simula as ações sem enviar ordens reais.
116
+
117
+ Retorna
118
+ -------
119
+ dict
120
+ Estatísticas da execução do panic close.
121
+ """
122
+ stats = {
123
+ "positions_total": 0,
124
+ "positions_closed": 0,
125
+ "orders_cancelled": 0,
126
+ "market_closed": False,
127
+ "trade_disabled": False,
128
+ "dry_run": dry_run,
129
+ "hardstop_executed": False,
130
+ }
131
+
132
+ while True:
133
+ market_fechado = False
134
+
135
+ with mt5_conexao():
136
+ if not _trade_permitido():
137
+ log.critical("[PANIC] Trading desabilitado na conta!")
138
+ stats["trade_disabled"] = True
139
+ break
140
+
141
+ positions = mt5.positions_get()
142
+ orders = mt5.orders_get()
143
+
144
+ if positions:
145
+ stats["positions_total"] = len(positions)
146
+
147
+ # 1️⃣ Fechamento de posições
148
+ if positions:
149
+ for pos in positions:
150
+ if not _market_aberto(pos.symbol):
151
+ market_fechado = True
152
+ log.critical(
153
+ f"[PANIC] Market fechado para {pos.symbol}"
154
+ )
155
+ continue
156
+
157
+ if _close_position(pos, dry_run=dry_run):
158
+ stats["positions_closed"] += 1
159
+
160
+ # 2️⃣ Cancelamento de ordens pendentes
161
+ if orders:
162
+ for ordem in orders:
163
+ if dry_run:
164
+ log.warning(
165
+ f"[PANIC][DRY] Cancelamento simulado | "
166
+ f"ticket={ordem.ticket}"
167
+ )
168
+ stats["orders_cancelled"] += 1
169
+ continue
170
+
171
+ request = {
172
+ "action": mt5.TRADE_ACTION_REMOVE,
173
+ "order": ordem.ticket,
174
+ }
175
+
176
+ result = mt5.order_send(request)
177
+
178
+ if not result:
179
+ log.error(
180
+ f"[PANIC] Falha ao cancelar ordem {ordem.ticket} | "
181
+ f"last_error={mt5.last_error()}"
182
+ )
183
+ continue
184
+
185
+ if result.retcode == mt5.TRADE_RETCODE_DONE:
186
+ stats["orders_cancelled"] += 1
187
+ log.warning(
188
+ f"[PANIC] Ordem cancelada | ticket={ordem.ticket}"
189
+ )
190
+ else:
191
+ log.error(
192
+ f"[PANIC] Falha ao cancelar ordem {ordem.ticket} | "
193
+ f"retcode={result.retcode}"
194
+ )
195
+
196
+ if not market_fechado:
197
+ break
198
+
199
+ stats["market_closed"] = True
200
+
201
+ if not retry_on_market_open:
202
+ break
203
+
204
+ log.critical(
205
+ f"[PANIC] Market fechado. Nova tentativa em {retry_interval}s..."
206
+ )
207
+ time.sleep(retry_interval)
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
+
216
+ log.critical(f"[PANIC] Resultado final: {stats}")
217
+ return stats
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mtcli-risco"
3
- version = "2.4.0"
3
+ version = "2.4.1"
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"}
@@ -1,36 +0,0 @@
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,15 +0,0 @@
1
- import os
2
- from mtcli.conf import config
3
-
4
-
5
- LOSS_LIMIT = float(
6
- os.getenv("LOSS_LIMIT", config["DEFAULT"].getfloat("loss_limit", fallback=-180.00))
7
- )
8
-
9
- STATUS_FILE = os.getenv(
10
- "STATUS_FILE",
11
- config["DEFAULT"].get("status_file", fallback="bloqueio.json"),
12
- )
13
- INTERVALO = int(
14
- os.getenv("INTERVALO", config["DEFAULT"].getint("intervalo", fallback=60))
15
- )
File without changes
File without changes