mtcli-risco 2.4.0__tar.gz → 2.4.2__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Valmir França
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,20 +1,25 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mtcli-risco
3
- Version: 2.4.0
3
+ Version: 2.4.2
4
4
  Summary: Plugin mtcli para controle de loss diário
5
- License-Expression: GPL-3.0
5
+ License-Expression: MIT
6
6
  License-File: LICENSE
7
- Author: Valmir França da Silva
7
+ Keywords: trading,risk manager,risk,metatrader5,mt5,cli,acessibilidade,screen reader friendly
8
+ Author: Valmir França
8
9
  Author-email: vfranca3@gmail.com
9
10
  Requires-Python: >=3.10,<3.14
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Financial and Insurance Industry
10
13
  Classifier: Programming Language :: Python :: 3
11
14
  Classifier: Programming Language :: Python :: 3.10
12
15
  Classifier: Programming Language :: Python :: 3.11
13
16
  Classifier: Programming Language :: Python :: 3.12
14
17
  Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Topic :: Office/Business :: Financial :: Investment
15
20
  Requires-Dist: click (>=8.3.1,<9.0.0)
16
21
  Requires-Dist: metatrader5 (>=5.0.5572,<6.0.0)
17
- Requires-Dist: mtcli (>=1.18.1)
22
+ Requires-Dist: mtcli (>=3.7.0)
18
23
  Project-URL: Documentation, https://mtcli-risco.readthedocs.io
19
24
  Project-URL: Homepage, https://github.com/vfranca/mtcli-risco
20
25
  Project-URL: Repository, https://github.com/vfranca/mtcli-risco
@@ -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,15 +1,40 @@
1
1
  [project]
2
2
  name = "mtcli-risco"
3
- version = "2.4.0"
3
+ version = "2.4.2"
4
4
  description = "Plugin mtcli para controle de loss diário"
5
5
  authors = [
6
- {name = "Valmir França da Silva",email = "vfranca3@gmail.com"}
6
+ {name = "Valmir França",email = "vfranca3@gmail.com"}
7
7
  ]
8
8
  readme = "README.md"
9
- license = "GPL-3.0"
9
+ license = "MIT"
10
10
  requires-python = ">=3.10,<3.14"
11
+
12
+
13
+ keywords = [
14
+ "trading",
15
+ "risk manager",
16
+ "risk",
17
+ "metatrader5",
18
+ "mt5",
19
+ "cli",
20
+ "acessibilidade",
21
+ "screen reader friendly"
22
+ ]
23
+
24
+ classifiers = [
25
+ "Development Status :: 5 - Production/Stable",
26
+ "Intended Audience :: Financial and Insurance Industry",
27
+ "Programming Language :: Python :: 3",
28
+ "Programming Language :: Python :: 3.10",
29
+ "Programming Language :: Python :: 3.11",
30
+ "Programming Language :: Python :: 3.12",
31
+ "Programming Language :: Python :: 3.13",
32
+ "Operating System :: OS Independent",
33
+ "Topic :: Office/Business :: Financial :: Investment",
34
+ ]
35
+
11
36
  dependencies = [
12
- "mtcli>=1.18.1",
37
+ "mtcli>=3.7.0",
13
38
  "click (>=8.3.1,<9.0.0)",
14
39
  "metatrader5 (>=5.0.5572,<6.0.0)"
15
40
  ]
@@ -21,7 +46,7 @@ repository = "https://github.com/vfranca/mtcli-risco"
21
46
  issues = "https://github.com/vfranca/mtcli-risco/issues"
22
47
 
23
48
  [project.entry-points."mtcli.plugins"]
24
- risco = "mtcli_risco.plugin:register"
49
+ mtcli-risco = "mtcli_risco.plugin:register"
25
50
 
26
51
  [build-system]
27
52
  requires = ["poetry-core>=2.0.0,<3.0.0"]