bbstrader 0.2.4__py3-none-any.whl

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.

Potentially problematic release.


This version of bbstrader might be problematic. Click here for more details.

@@ -0,0 +1,702 @@
1
+ import random
2
+ from datetime import datetime
3
+ from typing import Any, Dict, Optional, Union
4
+
5
+ import MetaTrader5 as Mt5
6
+ from scipy.stats import norm
7
+
8
+ from bbstrader.metatrader.account import Account
9
+ from bbstrader.metatrader.rates import Rates
10
+ from bbstrader.metatrader.utils import TIMEFRAMES, TimeFrame
11
+
12
+ _COMMD_SUPPORTED_ = [
13
+ "GOLD",
14
+ "XAUEUR",
15
+ "SILVER",
16
+ "BRENT",
17
+ "CRUDOIL",
18
+ "WTI",
19
+ "UKOIL",
20
+ "XAGEUR",
21
+ "XAGUSD",
22
+ "XAUAUD",
23
+ "XAUEUR",
24
+ "XAUUSD",
25
+ "XAUGBP",
26
+ "USOIL",
27
+ ]
28
+
29
+ _ADMIRAL_MARKETS_FUTURES_ = [
30
+ "#USTNote_",
31
+ "#Bund_",
32
+ "#USDX_",
33
+ "_AUS200_",
34
+ "_Canada60_",
35
+ "_SouthAfrica40_",
36
+ "_STXE600_",
37
+ "_EURO50_",
38
+ "_GER40_",
39
+ "_GermanyTech30_",
40
+ "_MidCapGER50_",
41
+ "_SWISS20_",
42
+ "_UK100_",
43
+ "_USNASDAQ100_",
44
+ "_YM_",
45
+ "_ES_",
46
+ "_CrudeOilUS_",
47
+ "_DUTCH25_",
48
+ "_FRANCE40_",
49
+ "_NORWAY25_",
50
+ "_SPAIN35_",
51
+ "_CrudeOilUK_",
52
+ "_XAU_",
53
+ "_HK50_",
54
+ "_HSCEI50_",
55
+ ]
56
+
57
+ __all__ = ["RiskManagement"]
58
+
59
+
60
+ class RiskManagement(Account):
61
+ """
62
+ The RiskManagement class provides foundational
63
+ risk management functionalities for trading activities.
64
+ It calculates risk levels, determines stop loss and take profit levels,
65
+ and ensures trading activities align with predefined risk parameters.
66
+
67
+ Exemple:
68
+ >>> risk_manager = RiskManagement(
69
+ ... symbol="EURUSD",
70
+ ... max_risk=5.0,
71
+ ... daily_risk=2.0,
72
+ ... max_trades=10,
73
+ ... std_stop=True,
74
+ ... account_leverage=True,
75
+ ... start_time="09:00",
76
+ ... finishing_time="17:00",
77
+ ... time_frame="1h"
78
+ ... )
79
+ >>> # Calculate risk level
80
+ >>> risk_level = risk_manager.risk_level()
81
+
82
+ >>> # Get appropriate lot size for a trade
83
+ >>> lot_size = risk_manager.get_lot()
84
+
85
+ >>> # Determine stop loss and take profit levels
86
+ >>> stop_loss = risk_manager.get_stop_loss()
87
+ >>> take_profit = risk_manager.get_take_profit()
88
+
89
+ >>> # Check if current risk is acceptable
90
+ >>> is_risk_acceptable = risk_manager.is_risk_ok()
91
+ """
92
+
93
+ def __init__(
94
+ self,
95
+ symbol: str,
96
+ max_risk: float = 10.0,
97
+ daily_risk: Optional[float] = None,
98
+ max_trades: Optional[int] = None,
99
+ std_stop: bool = False,
100
+ pchange_sl: Optional[float] = None,
101
+ var_level: float = 0.95,
102
+ var_time_frame: TimeFrame = "D1",
103
+ account_leverage: bool = True,
104
+ time_frame: TimeFrame = "D1",
105
+ start_time: str = "1:00",
106
+ finishing_time: str = "23:00",
107
+ sl: Optional[int] = None,
108
+ tp: Optional[int] = None,
109
+ be: Optional[int] = None,
110
+ rr: float = 1.5,
111
+ **kwargs,
112
+ ):
113
+ """
114
+ Initialize the RiskManagement class to manage risk in trading activities.
115
+
116
+ Args:
117
+ symbol (str): The symbol of the financial instrument to trade.
118
+ max_risk (float): The `maximum risk allowed` on the trading account.
119
+ daily_risk (float, optional): `Daily Max risk allowed`.
120
+ If Set to None it will be determine based on Maximum risk.
121
+ max_trades (int, optional): Maximum number of trades in a trading session.
122
+ If set to None it will be determine based on the timeframe of trading.
123
+ std_stop (bool, optional): If set to True, the Stop loss is calculated based
124
+ On `historical volatility` of the trading instrument. Defaults to False.
125
+ pchange_sl (float, optional): If set, the Stop loss is calculated based
126
+ On `percentage change` of the trading instrument.
127
+ var_level (float, optional): Confidence level for Value-at-Risk,e.g., 0.99 for 99% confidence interval.
128
+ The default is 0.95.
129
+ var_time_frame (str, optional): Time frame to use to calculate the VaR.
130
+ account_leverage (bool, optional): If set to True the account leverage will be used
131
+ In risk management setting. Defaults to False.
132
+ time_frame (str, optional): The time frame on which the program is working
133
+ `(1m, 3m, 5m, 10m, 15m, 30m, 1h, 2h, 4h, D1)`. Defaults to 'D1'.
134
+ start_time (str, optional): The starting time for the trading strategy
135
+ `(HH:MM, H an M do not star with 0)`. Defaults to "6:30".
136
+ finishing_time (str, optional): The finishing time for the trading strategy
137
+ `(HH:MM, H an M do not star with 0)`. Defaults to "19:30".
138
+ sl (int, optional): Stop Loss in points, Must be a positive number.
139
+ tp (int, optional): Take Profit in points, Must be a positive number.
140
+ be (int, optional): Break Even in points, Must be a positive number.
141
+ rr (float, optional): Risk reward ratio, Must be a positive number. Defaults to 1.5.
142
+
143
+ See `bbstrader.metatrader.account.check_mt5_connection()` for more details on how to connect to MT5 terminal.
144
+ """
145
+ super().__init__(**kwargs)
146
+
147
+ # Validation
148
+ if daily_risk is not None and daily_risk < 0:
149
+ raise ValueError("daily_risk must be a positive number")
150
+ if max_risk <= 0:
151
+ raise ValueError("max_risk must be a positive number")
152
+ if sl is not None and not isinstance(sl, int):
153
+ raise ValueError("sl must be an integer number")
154
+ if tp is not None and not isinstance(tp, int):
155
+ raise ValueError("tp must be an integer number")
156
+ if be is not None and (not isinstance(be, int) or be <= 0):
157
+ raise ValueError("be must be a positive integer number")
158
+ if time_frame not in TIMEFRAMES:
159
+ raise ValueError("Unsupported time frame {}".format(time_frame))
160
+ if var_time_frame not in TIMEFRAMES:
161
+ raise ValueError("Unsupported time frame {}".format(var_time_frame))
162
+
163
+ self.kwargs = kwargs
164
+ self.symbol = symbol
165
+ self.start_time = start_time
166
+ self.finishing_time = finishing_time
167
+ self.max_trades = max_trades
168
+ self.std = std_stop
169
+ self.pchange = pchange_sl
170
+ self.var_level = var_level
171
+ self.var_tf = var_time_frame
172
+ self.daily_dd = round(daily_risk, 5)
173
+ self.max_risk = max_risk
174
+ self.rr = rr
175
+ self.sl = sl
176
+ self.tp = tp
177
+ self.be = be
178
+
179
+ self.account_leverage = account_leverage
180
+ self.symbol_info = super().get_symbol_info(self.symbol)
181
+
182
+ self._tf = time_frame
183
+
184
+ @property
185
+ def dailydd(self) -> float:
186
+ return self.daily_dd
187
+
188
+ @dailydd.setter
189
+ def dailydd(self, value: float):
190
+ self.daily_dd = value
191
+
192
+ @property
193
+ def maxrisk(self) -> float:
194
+ return self.max_risk
195
+
196
+ @maxrisk.setter
197
+ def maxrisk(self, value: float):
198
+ self.max_risk = value
199
+
200
+ def _convert_time_frame(self, tf: str) -> int:
201
+ """Convert time frame to minutes"""
202
+ if tf == "D1":
203
+ tf_int = self.get_minutes()
204
+ elif "m" in tf:
205
+ tf_int = TIMEFRAMES[tf]
206
+ elif "h" in tf:
207
+ tf_int = int(tf[0]) * 60
208
+ elif tf == "W1":
209
+ tf_int = self.get_minutes() * 5
210
+ elif tf == "MN1":
211
+ tf_int = self.get_minutes() * 22
212
+ return tf_int
213
+
214
+ def risk_level(self) -> float:
215
+ """
216
+ Calculates the risk level of a trade
217
+
218
+ Returns:
219
+ - Risk level in the form of a float percentage.
220
+ """
221
+ account_info = self.get_account_info()
222
+ balance = account_info.balance
223
+ equity = account_info.equity
224
+ df = self.get_trades_history()
225
+ if df is None:
226
+ profit = 0
227
+ else:
228
+ profit_df = df.iloc[1:]
229
+ profit = profit_df["profit"].sum()
230
+ commisions = df["commission"].sum()
231
+ fees = df["fee"].sum()
232
+ swap = df["swap"].sum()
233
+ total_profit = commisions + fees + swap + profit
234
+ initial_balance = balance - total_profit
235
+ if balance != 0:
236
+ risk_alowed = (((equity - initial_balance) / equity) * 100) * -1
237
+ return round(risk_alowed, 2)
238
+ return 0.0
239
+
240
+ def get_lot(self) -> float:
241
+ """ "Get the approprite lot size for a trade"""
242
+ s_info = self.symbol_info
243
+ volume_step = s_info.volume_step
244
+ lot = self.currency_risk()["lot"]
245
+ steps = self._volume_step(volume_step)
246
+ if float(steps) >= float(1):
247
+ return round(lot, steps)
248
+ else:
249
+ return round(lot)
250
+
251
+ def _volume_step(self, value):
252
+ """Get the number of decimal places in a number"""
253
+
254
+ value_str = str(value)
255
+
256
+ if "." in value_str and value_str != "1.0":
257
+ decimal_index = value_str.index(".")
258
+ num_digits = len(value_str) - decimal_index - 1
259
+ return num_digits
260
+
261
+ elif value_str == "1.0":
262
+ return 0
263
+ else:
264
+ return 0
265
+
266
+ def max_trade(self) -> int:
267
+ """calculates the maximum number of trades allowed"""
268
+ minutes = self.get_minutes()
269
+ tf_int = self._convert_time_frame(self._tf)
270
+ if self.max_trades is not None:
271
+ max_trades = self.max_trades
272
+ else:
273
+ max_trades = round(minutes / tf_int)
274
+ return max(max_trades, 1)
275
+
276
+ def get_minutes(self) -> int:
277
+ """calculates the number of minutes between two times"""
278
+
279
+ start = datetime.strptime(self.start_time, "%H:%M")
280
+ end = datetime.strptime(self.finishing_time, "%H:%M")
281
+ return (end - start).total_seconds() // 60
282
+
283
+ def get_hours(self) -> int:
284
+ """Calculates the number of hours between two times"""
285
+
286
+ start = datetime.strptime(self.start_time, "%H:%M")
287
+ end = datetime.strptime(self.finishing_time, "%H:%M")
288
+ # Calculate the difference in hours
289
+ hours = (end - start).total_seconds() // 3600 # 1 hour = 3600 seconds
290
+
291
+ return hours
292
+
293
+ def get_std_stop(self):
294
+ """
295
+ Calculate the standard deviation-based stop loss level
296
+ for a given financial instrument.
297
+
298
+ Returns:
299
+ - Standard deviation-based stop loss level, rounded to the nearest point.
300
+ - 0 if the calculated stop loss is less than or equal to 0.
301
+ """
302
+ minutes = self.get_minutes()
303
+ tf_int = self._convert_time_frame(self._tf)
304
+ interval = round((minutes / tf_int) * 252)
305
+
306
+ rate = Rates(self.symbol, self._tf, 0, interval, **self.kwargs)
307
+ returns = rate.returns * 100
308
+ std = returns.std()
309
+ point = self.get_symbol_info(self.symbol).point
310
+ av_price = (self.symbol_info.bid + self.symbol_info.ask) / 2
311
+ price_interval = av_price * (100 - std) / 100
312
+ sl_point = float((av_price - price_interval) / point)
313
+ sl = round(sl_point)
314
+ min_sl = self.symbol_info.trade_stops_level * 2 + self.get_deviation()
315
+
316
+ return max(sl, min_sl)
317
+
318
+ def get_pchange_stop(self, pchange: Optional[float]):
319
+ """
320
+ Calculate the percentage change-based stop loss level
321
+ for a given financial instrument.
322
+
323
+ Args:
324
+ pchange (float): Percentage change in price to use for calculating stop loss level.
325
+ If pchange is set to None, the stop loss is calculate using std.
326
+
327
+ Returns:
328
+ - Percentage change-based stop loss level, rounded to the nearest point.
329
+ - 0 if the calculated stop loss is <= 0.
330
+ """
331
+ if pchange is not None:
332
+ av_price = (self.symbol_info.bid + self.symbol_info.ask) / 2
333
+ price_interval = av_price * (100 - pchange) / 100
334
+ point = self.get_symbol_info(self.symbol).point
335
+ sl_point = float((av_price - price_interval) / point)
336
+ sl = round(sl_point)
337
+ min_sl = self.symbol_info.trade_stops_level * 2 + self.get_deviation()
338
+ return max(sl, min_sl)
339
+ else:
340
+ # Use std as default pchange
341
+ return self.get_std_stop()
342
+
343
+ def calculate_var(self, tf: TimeFrame = "D1", c=0.95):
344
+ """
345
+ Calculate Value at Risk (VaR) for a given portfolio.
346
+
347
+ Args:
348
+ tf (str): Time frame to use to calculate volatility.
349
+ c (float): Confidence level for VaR calculation (default is 95%).
350
+
351
+ Returns:
352
+ - VaR value
353
+ """
354
+ minutes = self.get_minutes()
355
+ tf_int = self._convert_time_frame(tf)
356
+ interval = round((minutes / tf_int) * 252)
357
+
358
+ rate = Rates(self.symbol, tf, 0, interval, **self.kwargs)
359
+ returns = rate.returns * 100
360
+ p = self.get_account_info().margin_free
361
+ mu = returns.mean()
362
+ sigma = returns.std()
363
+ var = self.var_cov_var(p, c, mu, sigma)
364
+ return var
365
+
366
+ def var_cov_var(self, P: float, c: float, mu: float, sigma: float):
367
+ """
368
+ Variance-Covariance calculation of daily Value-at-Risk.
369
+
370
+ Args:
371
+ P (float): Portfolio value in USD.
372
+ c (float): Confidence level for Value-at-Risk,e.g., 0.99 for 99% confidence interval.
373
+ mu (float): Mean of the returns of the portfolio.
374
+ sigma (float): Standard deviation of the returns of the portfolio.
375
+
376
+ Returns:
377
+ - float: Value-at-Risk for the given portfolio.
378
+ """
379
+ alpha = norm.ppf(1 - c, mu, sigma)
380
+ return P - P * (alpha + 1)
381
+
382
+ def var_loss_value(self):
383
+ """
384
+ Calculate the stop-loss level based on VaR.
385
+
386
+ Notes:
387
+ The Var is Estimated using the Variance-Covariance method on the daily returns.
388
+ If you want to use the VaR for a different time frame .
389
+ """
390
+ P = self.get_account_info().margin_free
391
+ trade_risk = self.get_trade_risk()
392
+ loss_allowed = P * trade_risk / 100
393
+ var = self.calculate_var(c=self.var_level, tf=self.var_tf)
394
+ return min(var, loss_allowed)
395
+
396
+ def get_take_profit(self) -> int:
397
+ """calculates the take profit of a trade in points"""
398
+ deviation = self.get_deviation()
399
+ if self.tp is not None:
400
+ return self.tp + deviation
401
+ else:
402
+ return round(self.get_stop_loss() * self.rr)
403
+
404
+ def get_stop_loss(self) -> int:
405
+ """calculates the stop loss of a trade in points"""
406
+ min_sl = self.symbol_info.trade_stops_level * 2 + self.get_deviation()
407
+ if self.sl is not None:
408
+ return max(self.sl, min_sl)
409
+ elif self.sl is None and self.std:
410
+ sl = self.get_std_stop()
411
+ return max(sl, min_sl)
412
+ elif self.sl is None and not self.std:
413
+ risk = self.currency_risk()
414
+ if risk["trade_loss"] != 0:
415
+ sl = round((risk["currency_risk"] / risk["trade_loss"]))
416
+ return max(sl, min_sl)
417
+ return min_sl
418
+
419
+ def get_currency_risk(self) -> float:
420
+ """calculates the currency risk of a trade"""
421
+ return round(self.currency_risk()["currency_risk"], 2)
422
+
423
+ def expected_profit(self):
424
+ """Calculate the expected profit per trade"""
425
+ risk = self.get_currency_risk()
426
+ return round(risk * self.rr, 2)
427
+
428
+ def volume(self):
429
+ """Volume per trade"""
430
+
431
+ return self.currency_risk()["volume"]
432
+
433
+ def currency_risk(self) -> Dict[str, Union[int, float, Any]]:
434
+ """
435
+ Calculates the currency risk of a trade.
436
+
437
+ Returns:
438
+ Dict[str, Union[int, float, Any]]: A dictionary containing the following keys:
439
+
440
+ - `'currency_risk'`: Dollar amount risk on a single trade.
441
+ - `'trade_loss'`: Loss value per tick in dollars.
442
+ - `'trade_profit'`: Profit value per tick in dollars.
443
+ - `'volume'`: Contract size multiplied by the average price.
444
+ - `'lot'`: Lot size per trade.
445
+ """
446
+ s_info = self.symbol_info
447
+
448
+ laverage = self.get_leverage(self.account_leverage)
449
+ contract_size = s_info.trade_contract_size
450
+
451
+ av_price = (s_info.bid + s_info.ask) / 2
452
+ trade_risk = self.get_trade_risk()
453
+ symbol_type = self.get_symbol_type(self.symbol)
454
+ FX = symbol_type == "FX"
455
+ COMD = symbol_type == "COMD"
456
+ FUT = symbol_type == "FUT"
457
+ CRYPTO = symbol_type == "CRYPTO"
458
+ if COMD:
459
+ supported = _COMMD_SUPPORTED_
460
+ if "." in self.symbol:
461
+ symbol = self.symbol.split(".")[0]
462
+ elif self.symbol.endswith("xx"):
463
+ symbol = self.symbol[:-2]
464
+ elif self.symbol.endswith('-'):
465
+ symbol = self.symbol[:-1]
466
+ else:
467
+ symbol = self.symbol
468
+ if symbol in supported:
469
+ raise ValueError(
470
+ f"Currency risk calculation for '{self.symbol}' is not a currently supported. \n"
471
+ f"Supported commodity symbols are: {', '.join(supported)}"
472
+ )
473
+ if FUT:
474
+ supported = _ADMIRAL_MARKETS_FUTURES_
475
+ if self.symbol[:-2] not in supported:
476
+ raise ValueError(
477
+ f"Currency risk calculation for '{self.symbol}' is not a currently supported. \n"
478
+ f"Supported future symbols are: {', '.join(supported)}"
479
+ )
480
+ if trade_risk > 0:
481
+ currency_risk = round(self.var_loss_value(), 5)
482
+ volume = round(currency_risk * laverage)
483
+ try:
484
+ _lot = round((volume / (contract_size * av_price)), 2)
485
+ except ZeroDivisionError:
486
+ _lot = 0.0
487
+ lot = self._check_lot(_lot)
488
+ if COMD and contract_size > 1:
489
+ # lot = volume / av_price / contract_size
490
+ try:
491
+ lot = volume / av_price / contract_size
492
+ except ZeroDivisionError:
493
+ lot = 0.0
494
+ lot = self._check_lot(_lot)
495
+ if FX:
496
+ try:
497
+ __lot = round((volume / contract_size), 2)
498
+ except ZeroDivisionError:
499
+ __lot = 0.0
500
+ lot = self._check_lot(__lot)
501
+
502
+ tick_value = s_info.trade_tick_value
503
+ tick_value_loss = s_info.trade_tick_value_loss
504
+ tick_value_profit = s_info.trade_tick_value_profit
505
+
506
+ if COMD or FUT or CRYPTO and contract_size > 1:
507
+ tick_value_loss = tick_value_loss / contract_size
508
+ tick_value_profit = tick_value_profit / contract_size
509
+ if tick_value == 0 or tick_value_loss == 0 or tick_value_profit == 0:
510
+ raise ValueError(
511
+ f"""The Tick Values for {self.symbol} is 0.0
512
+ We can not procced with currency risk calculation
513
+ Please check your Broker trade conditions
514
+ and symbol specifications for {self.symbol}"""
515
+ )
516
+
517
+ # Case where the stop loss is given
518
+ if self.sl is not None:
519
+ trade_loss = currency_risk / self.sl
520
+ if self.tp is not None:
521
+ trade_profit = (currency_risk * (self.tp // self.sl)) / self.tp
522
+ else:
523
+ trade_profit = (currency_risk * self.rr) / (self.sl * self.rr)
524
+ lot_ = round(trade_loss / (contract_size * tick_value_loss), 2)
525
+ lot = self._check_lot(lot_)
526
+ volume = round(lot * contract_size * av_price)
527
+
528
+ if COMD or CRYPTO and contract_size > 1:
529
+ # trade_risk = points * tick_value_loss * lot
530
+ lot = currency_risk / (self.sl * tick_value_loss * contract_size)
531
+ lot = self._check_lot(lot)
532
+ trade_loss = lot * contract_size * tick_value_loss
533
+
534
+ if FX:
535
+ volume = round((trade_loss * contract_size) / tick_value_loss)
536
+ __lot = round((volume / contract_size), 2)
537
+ lot = self._check_lot(__lot)
538
+
539
+ # Case where the stantard deviation is used
540
+ elif self.std and self.pchange is None and self.sl is None:
541
+ sl = self.get_std_stop()
542
+ infos = self._std_pchange_stop(
543
+ currency_risk, sl, contract_size, tick_value_loss
544
+ )
545
+ trade_loss, trade_profit, lot, volume = infos
546
+
547
+ # Case where the stop loss is based on a percentage change
548
+ elif self.pchange is not None and not self.std and self.sl is None:
549
+ sl = self.get_pchange_stop(self.pchange)
550
+ infos = self._std_pchange_stop(
551
+ currency_risk, sl, contract_size, tick_value_loss
552
+ )
553
+ trade_loss, trade_profit, lot, volume = infos
554
+
555
+ # Default cases
556
+ else:
557
+ # Handle FX
558
+ if FX:
559
+ trade_loss = tick_value_loss * (volume / contract_size)
560
+ trade_profit = tick_value_profit * (volume / contract_size)
561
+ else:
562
+ trade_loss = (lot * contract_size) * tick_value_loss
563
+ trade_profit = (lot * contract_size) * tick_value_profit
564
+
565
+ # if self.get_symbol_type(self.symbol) == 'IDX':
566
+ # rates = self.get_currency_rates(self.symbol)
567
+ # if rates['mc'] == rates['pc'] == 'JPY':
568
+ # lot = lot * contract_size
569
+ # lot = self._check_lot(lot)
570
+ # volume = round(lot * av_price * contract_size)
571
+ # if contract_size == 1:
572
+ # volume = round(lot * av_price)
573
+
574
+ return {
575
+ "currency_risk": currency_risk,
576
+ "trade_loss": trade_loss,
577
+ "trade_profit": trade_profit,
578
+ "volume": round(volume),
579
+ "lot": lot,
580
+ }
581
+ else:
582
+ return {
583
+ "currency_risk": 0.0,
584
+ "trade_loss": 0.0,
585
+ "trade_profit": 0.0,
586
+ "volume": 0,
587
+ "lot": 0.01,
588
+ }
589
+
590
+ def _std_pchange_stop(self, currency_risk, sl, size, loss):
591
+ """
592
+ Calculate the stop loss level based on standard deviation or percentage change.
593
+
594
+ Args:
595
+ currency_risk (float): The amount of risk in dollars.
596
+ sl (int): Stop loss level in points.
597
+ size (int): Contract size.
598
+ loss (float): Loss value per tick in dollars.
599
+
600
+ """
601
+ trade_loss = currency_risk / sl
602
+ trade_profit = (currency_risk * self.rr) / (sl * self.rr)
603
+ av_price = (self.symbol_info.bid + self.symbol_info.ask) / 2
604
+ _lot = round(trade_loss / (size * loss), 2)
605
+ lot = self._check_lot(_lot)
606
+
607
+ volume = round(lot * size * av_price)
608
+ if self.get_symbol_type(self.symbol) == "FX":
609
+ volume = round((trade_loss * size) / loss)
610
+ __lot = round((volume / size), 2)
611
+ lot = self._check_lot(__lot)
612
+
613
+ if (
614
+ self.get_symbol_type(self.symbol) == "COMD"
615
+ or self.get_symbol_type(self.symbol) == "CRYPTO"
616
+ and size > 1
617
+ ):
618
+ lot = currency_risk / (sl * loss * size)
619
+ lot = self._check_lot(lot)
620
+ trade_loss = lot * size * loss
621
+ volume = round(lot * size * av_price)
622
+
623
+ return trade_loss, trade_profit, lot, volume
624
+
625
+ def _check_lot(self, lot: float) -> float:
626
+ if lot > self.symbol_info.volume_max:
627
+ return self.symbol_info.volume_max / 2
628
+ elif lot < self.symbol_info.volume_min:
629
+ return self.symbol_info.volume_min
630
+ return lot
631
+
632
+ def get_trade_risk(self):
633
+ """Calculate risk per trade as percentage"""
634
+ total_risk = self.risk_level()
635
+ max_trades = self.max_trade()
636
+ if total_risk < self.max_risk:
637
+ if self.daily_dd is not None:
638
+ trade_risk = self.daily_dd / max_trades
639
+ else:
640
+ trade_risk = (self.max_risk - total_risk) / max_trades
641
+ return trade_risk
642
+ else:
643
+ return 0
644
+
645
+ def get_leverage(self, account: bool) -> int:
646
+ """
647
+ get the Laverage for each symbol
648
+
649
+ Args:
650
+ account (bool): If set to True, the account leverage will be used
651
+ in risk managment setting
652
+ Notes:
653
+ For FX symbols, account leverage is used by default.
654
+ For Other instruments the account leverage is used if any error
655
+ occurs in leverage calculation.
656
+ """
657
+ AL = self.get_account_info().leverage
658
+ if account:
659
+ return AL
660
+
661
+ if self.get_symbol_type(self.symbol) == "FX":
662
+ return AL
663
+ else:
664
+ s_info = self.symbol_info
665
+ volume_min = s_info.volume_min
666
+ contract_size = s_info.trade_contract_size
667
+ av_price = (s_info.bid + s_info.ask) / 2
668
+ action = random.choice([Mt5.ORDER_TYPE_BUY, Mt5.ORDER_TYPE_SELL])
669
+ margin = Mt5.order_calc_margin(action, self.symbol, volume_min, av_price)
670
+ if margin is None:
671
+ return AL
672
+ try:
673
+ leverage = (volume_min * contract_size * av_price) / margin
674
+ return round(leverage)
675
+ except ZeroDivisionError:
676
+ return AL
677
+
678
+ def get_deviation(self) -> int:
679
+ return self.symbol_info.spread
680
+
681
+ def get_break_even(self) -> int:
682
+ if self.be is not None:
683
+ if isinstance(self.be, int):
684
+ return self.be
685
+ elif isinstance(self.be, float):
686
+ return self.get_pchange_stop(self.be)
687
+ else:
688
+ stop = self.get_stop_loss()
689
+ spread = self.get_symbol_info(self.symbol).spread
690
+ if stop <= 100:
691
+ be = round((stop + spread) * 0.5)
692
+ elif stop > 100 and stop <= 150:
693
+ be = round((stop + spread) * 0.35)
694
+ elif stop > 150:
695
+ be = round((stop + spread) * 0.25)
696
+ return be
697
+
698
+ def is_risk_ok(self) -> bool:
699
+ if self.risk_level() <= self.max_risk:
700
+ return True
701
+ else:
702
+ return False