bbstrader 0.3.3__py3-none-any.whl → 0.3.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.
- bbstrader/__main__.py +10 -2
- bbstrader/apps/__init__.py +0 -0
- bbstrader/apps/_copier.py +664 -0
- bbstrader/btengine/strategy.py +163 -90
- bbstrader/core/utils.py +5 -3
- bbstrader/metatrader/account.py +169 -29
- bbstrader/metatrader/analysis.py +7 -5
- bbstrader/metatrader/copier.py +4 -0
- bbstrader/metatrader/scripts.py +15 -2
- bbstrader/metatrader/utils.py +64 -0
- bbstrader/models/ml.py +8 -5
- bbstrader/trading/execution.py +9 -8
- {bbstrader-0.3.3.dist-info → bbstrader-0.3.4.dist-info}/METADATA +4 -4
- {bbstrader-0.3.3.dist-info → bbstrader-0.3.4.dist-info}/RECORD +18 -16
- {bbstrader-0.3.3.dist-info → bbstrader-0.3.4.dist-info}/WHEEL +0 -0
- {bbstrader-0.3.3.dist-info → bbstrader-0.3.4.dist-info}/entry_points.txt +0 -0
- {bbstrader-0.3.3.dist-info → bbstrader-0.3.4.dist-info}/licenses/LICENSE +0 -0
- {bbstrader-0.3.3.dist-info → bbstrader-0.3.4.dist-info}/top_level.txt +0 -0
bbstrader/btengine/strategy.py
CHANGED
|
@@ -11,10 +11,12 @@ from loguru import logger
|
|
|
11
11
|
|
|
12
12
|
from bbstrader.btengine.data import DataHandler
|
|
13
13
|
from bbstrader.btengine.event import Events, FillEvent, SignalEvent
|
|
14
|
+
from bbstrader.metatrader.trade import generate_signal, TradeAction
|
|
14
15
|
from bbstrader.config import BBSTRADER_DIR
|
|
15
16
|
from bbstrader.metatrader import (
|
|
16
17
|
Account,
|
|
17
18
|
AdmiralMarktsGroup,
|
|
19
|
+
MetaQuotes,
|
|
18
20
|
PepperstoneGroupLimited,
|
|
19
21
|
TradeOrder,
|
|
20
22
|
Rates,
|
|
@@ -78,7 +80,16 @@ class MT5Strategy(Strategy):
|
|
|
78
80
|
in order to avoid naming collusion.
|
|
79
81
|
"""
|
|
80
82
|
tf: str
|
|
83
|
+
id: int
|
|
84
|
+
ID: int
|
|
85
|
+
|
|
81
86
|
max_trades: Dict[str, int]
|
|
87
|
+
risk_budget: Dict[str, float] | str | None
|
|
88
|
+
|
|
89
|
+
_orders: Dict[str, Dict[str, List[SignalEvent]]]
|
|
90
|
+
_positions: Dict[str, Dict[str, int | float]]
|
|
91
|
+
_trades: Dict[str, Dict[str, int]]
|
|
92
|
+
|
|
82
93
|
def __init__(
|
|
83
94
|
self,
|
|
84
95
|
events: Queue = None,
|
|
@@ -104,13 +115,19 @@ class MT5Strategy(Strategy):
|
|
|
104
115
|
self.data = bars
|
|
105
116
|
self.symbols = symbol_list
|
|
106
117
|
self.mode = mode
|
|
107
|
-
self.
|
|
118
|
+
if self.mode not in [TradingMode.BACKTEST, TradingMode.LIVE]:
|
|
119
|
+
raise ValueError(f"Mode must be an instance of {type(TradingMode)} not {type(self.mode)}")
|
|
120
|
+
|
|
108
121
|
self.risk_budget = self._check_risk_budget(**kwargs)
|
|
122
|
+
|
|
109
123
|
self.max_trades = kwargs.get("max_trades", {s: 1 for s in self.symbols})
|
|
110
124
|
self.tf = kwargs.get("time_frame", "D1")
|
|
111
125
|
self.logger = kwargs.get("logger") or logger
|
|
126
|
+
|
|
112
127
|
if self.mode == TradingMode.BACKTEST:
|
|
128
|
+
self._porfolio_value = None
|
|
113
129
|
self._initialize_portfolio()
|
|
130
|
+
|
|
114
131
|
self.kwargs = kwargs
|
|
115
132
|
self.periodes = 0
|
|
116
133
|
|
|
@@ -170,19 +187,17 @@ class MT5Strategy(Strategy):
|
|
|
170
187
|
return weights
|
|
171
188
|
|
|
172
189
|
def _initialize_portfolio(self):
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
self.
|
|
176
|
-
self._positions: Dict[str, Dict[str, int | float]] = {}
|
|
177
|
-
self._trades: Dict[str, Dict[str, int]] = {}
|
|
190
|
+
self._orders = {}
|
|
191
|
+
self._positions = {}
|
|
192
|
+
self._trades = {}
|
|
178
193
|
for symbol in self.symbols:
|
|
179
194
|
self._positions[symbol] = {}
|
|
180
195
|
self._orders[symbol] = {}
|
|
181
196
|
self._trades[symbol] = {}
|
|
182
|
-
for position in
|
|
197
|
+
for position in ["LONG", "SHORT"]:
|
|
183
198
|
self._trades[symbol][position] = 0
|
|
184
199
|
self._positions[symbol][position] = 0.0
|
|
185
|
-
for order in
|
|
200
|
+
for order in ["BLMT", "BSTP", "BSTPLMT", "SLMT", "SSTP", "SSTPLMT"]:
|
|
186
201
|
self._orders[symbol][order] = []
|
|
187
202
|
self._holdings = {s: 0.0 for s in self.symbols}
|
|
188
203
|
|
|
@@ -236,6 +251,54 @@ class MT5Strategy(Strategy):
|
|
|
236
251
|
"""
|
|
237
252
|
pass
|
|
238
253
|
|
|
254
|
+
def signal(self, signal: int, symbol: str) -> TradeSignal:
|
|
255
|
+
"""
|
|
256
|
+
Generate a ``TradeSignal`` object based on the signal value.
|
|
257
|
+
Args:
|
|
258
|
+
signal : An integer value representing the signal type:
|
|
259
|
+
0: BUY
|
|
260
|
+
1: SELL
|
|
261
|
+
2: EXIT_LONG
|
|
262
|
+
3: EXIT_SHORT
|
|
263
|
+
4: EXIT_ALL_POSITIONS
|
|
264
|
+
5: EXIT_ALL_ORDERS
|
|
265
|
+
6: EXIT_STOP
|
|
266
|
+
7: EXIT_LIMIT
|
|
267
|
+
|
|
268
|
+
symbol : The symbol for the trade.
|
|
269
|
+
|
|
270
|
+
Returns:
|
|
271
|
+
TradeSignal : A ``TradeSignal`` object representing the trade signal.
|
|
272
|
+
|
|
273
|
+
Note:
|
|
274
|
+
This generate only common signals. For more complex signals, use `generate_signal` directly.
|
|
275
|
+
|
|
276
|
+
Raises:
|
|
277
|
+
ValueError : If the signal value is not between 0 and 7.
|
|
278
|
+
"""
|
|
279
|
+
signal_id = getattr(self, "id", None) or getattr(self, "ID")
|
|
280
|
+
|
|
281
|
+
match signal:
|
|
282
|
+
case 0:
|
|
283
|
+
return generate_signal(signal_id, symbol, TradeAction.BUY)
|
|
284
|
+
case 1:
|
|
285
|
+
return generate_signal(signal_id, symbol, TradeAction.SELL)
|
|
286
|
+
case 2:
|
|
287
|
+
return generate_signal(signal_id, symbol, TradeAction.EXIT_LONG)
|
|
288
|
+
case 3:
|
|
289
|
+
return generate_signal(signal_id, symbol, TradeAction.EXIT_SHORT)
|
|
290
|
+
case 4:
|
|
291
|
+
return generate_signal(signal_id, symbol, TradeAction.EXIT_ALL_POSITIONS)
|
|
292
|
+
case 5:
|
|
293
|
+
return generate_signal(signal_id, symbol, TradeAction.EXIT_ALL_ORDERS)
|
|
294
|
+
case 6:
|
|
295
|
+
return generate_signal(signal_id, symbol, TradeAction.EXIT_STOP)
|
|
296
|
+
case 7:
|
|
297
|
+
return generate_signal(signal_id, symbol, TradeAction.EXIT_LIMIT)
|
|
298
|
+
case _:
|
|
299
|
+
raise ValueError(f"Invalid signal value: {signal}. Must be an integer between 0 and 7.")
|
|
300
|
+
|
|
301
|
+
|
|
239
302
|
def perform_period_end_checks(self, *args, **kwargs):
|
|
240
303
|
"""
|
|
241
304
|
Some strategies may require additional checks at the end of the period,
|
|
@@ -551,75 +614,75 @@ class MT5Strategy(Strategy):
|
|
|
551
614
|
]
|
|
552
615
|
logmsg(order, log_label, symbol, dtime)
|
|
553
616
|
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
617
|
+
for symbol in self.symbols:
|
|
618
|
+
dtime = self.data.get_latest_bar_datetime(symbol)
|
|
619
|
+
latest_close = self.data.get_latest_bar_value(symbol, "close")
|
|
620
|
+
|
|
621
|
+
process_orders(
|
|
622
|
+
"BLMT",
|
|
623
|
+
lambda o: latest_close <= o.price,
|
|
624
|
+
lambda o: self.buy_mkt(
|
|
625
|
+
o.strategy_id, symbol, o.price, o.quantity, dtime
|
|
626
|
+
),
|
|
627
|
+
"BUY LIMIT",
|
|
628
|
+
symbol,
|
|
629
|
+
dtime,
|
|
630
|
+
)
|
|
631
|
+
|
|
632
|
+
process_orders(
|
|
633
|
+
"SLMT",
|
|
634
|
+
lambda o: latest_close >= o.price,
|
|
635
|
+
lambda o: self.sell_mkt(
|
|
636
|
+
o.strategy_id, symbol, o.price, o.quantity, dtime
|
|
637
|
+
),
|
|
638
|
+
"SELL LIMIT",
|
|
639
|
+
symbol,
|
|
640
|
+
dtime,
|
|
641
|
+
)
|
|
642
|
+
|
|
643
|
+
process_orders(
|
|
644
|
+
"BSTP",
|
|
645
|
+
lambda o: latest_close >= o.price,
|
|
646
|
+
lambda o: self.buy_mkt(
|
|
647
|
+
o.strategy_id, symbol, o.price, o.quantity, dtime
|
|
648
|
+
),
|
|
649
|
+
"BUY STOP",
|
|
650
|
+
symbol,
|
|
651
|
+
dtime,
|
|
652
|
+
)
|
|
653
|
+
|
|
654
|
+
process_orders(
|
|
655
|
+
"SSTP",
|
|
656
|
+
lambda o: latest_close <= o.price,
|
|
657
|
+
lambda o: self.sell_mkt(
|
|
658
|
+
o.strategy_id, symbol, o.price, o.quantity, dtime
|
|
659
|
+
),
|
|
660
|
+
"SELL STOP",
|
|
661
|
+
symbol,
|
|
662
|
+
dtime,
|
|
663
|
+
)
|
|
664
|
+
|
|
665
|
+
process_orders(
|
|
666
|
+
"BSTPLMT",
|
|
667
|
+
lambda o: latest_close >= o.price,
|
|
668
|
+
lambda o: self.buy_limit(
|
|
669
|
+
o.strategy_id, symbol, o.stoplimit, o.quantity, dtime
|
|
670
|
+
),
|
|
671
|
+
"BUY STOP LIMIT",
|
|
672
|
+
symbol,
|
|
673
|
+
dtime,
|
|
674
|
+
)
|
|
675
|
+
|
|
676
|
+
process_orders(
|
|
677
|
+
"SSTPLMT",
|
|
678
|
+
lambda o: latest_close <= o.price,
|
|
679
|
+
lambda o: self.sell_limit(
|
|
680
|
+
o.strategy_id, symbol, o.stoplimit, o.quantity, dtime
|
|
681
|
+
),
|
|
682
|
+
"SELL STOP LIMIT",
|
|
683
|
+
symbol,
|
|
684
|
+
dtime,
|
|
685
|
+
)
|
|
623
686
|
|
|
624
687
|
@staticmethod
|
|
625
688
|
def calculate_pct_change(current_price, lh_price) -> float:
|
|
@@ -803,13 +866,10 @@ class MT5Strategy(Strategy):
|
|
|
803
866
|
elif len(prices) in range(2, self.max_trades[asset] + 1):
|
|
804
867
|
price = np.mean(prices)
|
|
805
868
|
if price is not None:
|
|
806
|
-
if
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
and abs(self.calculate_pct_change(bid, price)) >= th
|
|
811
|
-
):
|
|
812
|
-
return True
|
|
869
|
+
if position == 0:
|
|
870
|
+
return self.calculate_pct_change(ask, price) >= th
|
|
871
|
+
elif position == 1:
|
|
872
|
+
return self.calculate_pct_change(bid, price) <= -th
|
|
813
873
|
return False
|
|
814
874
|
|
|
815
875
|
@staticmethod
|
|
@@ -834,9 +894,7 @@ class MT5Strategy(Strategy):
|
|
|
834
894
|
dt_to : The converted datetime.
|
|
835
895
|
"""
|
|
836
896
|
from_tz = pytz.timezone(from_tz)
|
|
837
|
-
if isinstance(dt, datetime):
|
|
838
|
-
dt = pd.to_datetime(dt, unit="s")
|
|
839
|
-
elif isinstance(dt, int):
|
|
897
|
+
if isinstance(dt, (datetime, int)):
|
|
840
898
|
dt = pd.to_datetime(dt, unit="s")
|
|
841
899
|
if dt.tzinfo is None:
|
|
842
900
|
dt = dt.tz_localize(from_tz)
|
|
@@ -862,20 +920,35 @@ class MT5Strategy(Strategy):
|
|
|
862
920
|
Returns:
|
|
863
921
|
mt5_equivalent : The MetaTrader 5 equivalent symbols for the symbols in the list.
|
|
864
922
|
"""
|
|
923
|
+
|
|
865
924
|
account = Account(**kwargs)
|
|
866
925
|
mt5_symbols = account.get_symbols(symbol_type=symbol_type)
|
|
867
926
|
mt5_equivalent = []
|
|
868
|
-
|
|
927
|
+
|
|
928
|
+
def _get_admiral_symbols():
|
|
869
929
|
for s in mt5_symbols:
|
|
870
930
|
_s = s[1:] if s[0] in string.punctuation else s
|
|
871
931
|
for symbol in symbols:
|
|
872
932
|
if _s.split(".")[0] == symbol or _s.split("_")[0] == symbol:
|
|
873
933
|
mt5_equivalent.append(s)
|
|
874
|
-
|
|
875
|
-
|
|
934
|
+
|
|
935
|
+
def _get_pepperstone_symbols():
|
|
936
|
+
for s in mt5_symbols:
|
|
876
937
|
for symbol in symbols:
|
|
877
938
|
if s.split(".")[0] == symbol:
|
|
878
939
|
mt5_equivalent.append(s)
|
|
940
|
+
|
|
941
|
+
if account.broker == MetaQuotes():
|
|
942
|
+
if "Admiral" in account.server:
|
|
943
|
+
_get_admiral_symbols()
|
|
944
|
+
elif "Pepperstone" in account.server:
|
|
945
|
+
_get_pepperstone_symbols()
|
|
946
|
+
|
|
947
|
+
elif account.broker == AdmiralMarktsGroup():
|
|
948
|
+
_get_admiral_symbols()
|
|
949
|
+
elif account.broker == PepperstoneGroupLimited():
|
|
950
|
+
_get_pepperstone_symbols()
|
|
951
|
+
|
|
879
952
|
return mt5_equivalent
|
|
880
953
|
|
|
881
954
|
|
bbstrader/core/utils.py
CHANGED
|
@@ -66,9 +66,11 @@ def dict_from_ini(file_path, sections: str | List[str] = None) -> Dict[str, Any]
|
|
|
66
66
|
Returns:
|
|
67
67
|
A dictionary containing the INI file contents with proper data types.
|
|
68
68
|
"""
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
69
|
+
try:
|
|
70
|
+
config = configparser.ConfigParser(interpolation=None)
|
|
71
|
+
config.read(file_path)
|
|
72
|
+
except Exception:
|
|
73
|
+
raise
|
|
72
74
|
ini_dict = {}
|
|
73
75
|
for section in config.sections():
|
|
74
76
|
ini_dict[section] = {
|
bbstrader/metatrader/account.py
CHANGED
|
@@ -1,19 +1,28 @@
|
|
|
1
1
|
import os
|
|
2
2
|
import re
|
|
3
3
|
import urllib.request
|
|
4
|
-
from datetime import datetime
|
|
4
|
+
from datetime import datetime
|
|
5
5
|
from typing import Any, Dict, List, Literal, Optional, Tuple, Union
|
|
6
6
|
|
|
7
|
+
import numpy as np
|
|
7
8
|
import pandas as pd
|
|
9
|
+
from currency_converter import SINGLE_DAY_ECB_URL, CurrencyConverter
|
|
10
|
+
from numpy.typing import NDArray
|
|
11
|
+
|
|
8
12
|
from bbstrader.metatrader.utils import (
|
|
13
|
+
TIMEFRAMES,
|
|
9
14
|
AccountInfo,
|
|
10
15
|
BookInfo,
|
|
11
16
|
InvalidBroker,
|
|
12
17
|
OrderCheckResult,
|
|
13
18
|
OrderSentResult,
|
|
19
|
+
RateDtype,
|
|
20
|
+
RateInfo,
|
|
14
21
|
SymbolInfo,
|
|
15
22
|
SymbolType,
|
|
16
23
|
TerminalInfo,
|
|
24
|
+
TickDtype,
|
|
25
|
+
TickFlag,
|
|
17
26
|
TickInfo,
|
|
18
27
|
TradeDeal,
|
|
19
28
|
TradeOrder,
|
|
@@ -21,7 +30,6 @@ from bbstrader.metatrader.utils import (
|
|
|
21
30
|
TradeRequest,
|
|
22
31
|
raise_mt5_error,
|
|
23
32
|
)
|
|
24
|
-
from currency_converter import SINGLE_DAY_ECB_URL, CurrencyConverter
|
|
25
33
|
|
|
26
34
|
try:
|
|
27
35
|
import MetaTrader5 as mt5
|
|
@@ -170,7 +178,7 @@ def check_mt5_connection(
|
|
|
170
178
|
if account_info is not None:
|
|
171
179
|
if account_info.login == login and account_info.server == server:
|
|
172
180
|
return True
|
|
173
|
-
|
|
181
|
+
|
|
174
182
|
init = False
|
|
175
183
|
if path is None and (login or password or server):
|
|
176
184
|
raise ValueError(
|
|
@@ -517,7 +525,7 @@ class Account(object):
|
|
|
517
525
|
"""Helper function to print account info"""
|
|
518
526
|
self._show_info(self.get_account_info, "account")
|
|
519
527
|
|
|
520
|
-
def get_terminal_info(self, show=False) ->
|
|
528
|
+
def get_terminal_info(self, show=False) -> TerminalInfo | None:
|
|
521
529
|
"""
|
|
522
530
|
Get the connected MetaTrader 5 client terminal status and settings.
|
|
523
531
|
|
|
@@ -965,7 +973,7 @@ class Account(object):
|
|
|
965
973
|
futures_types["bonds"].append(info.name)
|
|
966
974
|
return futures_types[category]
|
|
967
975
|
|
|
968
|
-
def get_symbol_info(self, symbol: str) ->
|
|
976
|
+
def get_symbol_info(self, symbol: str) -> SymbolInfo | None:
|
|
969
977
|
"""Get symbol properties
|
|
970
978
|
|
|
971
979
|
Args:
|
|
@@ -998,6 +1006,14 @@ class Account(object):
|
|
|
998
1006
|
msg = self._symbol_info_msg(symbol)
|
|
999
1007
|
raise_mt5_error(message=f"{str(e)} {msg}")
|
|
1000
1008
|
|
|
1009
|
+
def _symbol_info_msg(self, symbol):
|
|
1010
|
+
return (
|
|
1011
|
+
f"No history found for {symbol} in Market Watch.\n"
|
|
1012
|
+
f"* Ensure {symbol} is selected and displayed in the Market Watch window.\n"
|
|
1013
|
+
f"* See https://www.metatrader5.com/en/terminal/help/trading/market_watch\n"
|
|
1014
|
+
f"* Ensure the symbol name is correct.\n"
|
|
1015
|
+
)
|
|
1016
|
+
|
|
1001
1017
|
def show_symbol_info(self, symbol: str):
|
|
1002
1018
|
"""
|
|
1003
1019
|
Print symbol properties
|
|
@@ -1007,15 +1023,7 @@ class Account(object):
|
|
|
1007
1023
|
"""
|
|
1008
1024
|
self._show_info(self.get_symbol_info, "symbol", symbol=symbol)
|
|
1009
1025
|
|
|
1010
|
-
def
|
|
1011
|
-
return (
|
|
1012
|
-
f"No history found for {symbol} in Market Watch.\n"
|
|
1013
|
-
f"* Ensure {symbol} is selected and displayed in the Market Watch window.\n"
|
|
1014
|
-
f"* See https://www.metatrader5.com/en/terminal/help/trading/market_watch\n"
|
|
1015
|
-
f"* Ensure the symbol name is correct.\n"
|
|
1016
|
-
)
|
|
1017
|
-
|
|
1018
|
-
def get_tick_info(self, symbol: str) -> Union[TickInfo, None]:
|
|
1026
|
+
def get_tick_info(self, symbol: str) -> TickInfo | None:
|
|
1019
1027
|
"""Get symbol tick properties
|
|
1020
1028
|
|
|
1021
1029
|
Args:
|
|
@@ -1057,7 +1065,148 @@ class Account(object):
|
|
|
1057
1065
|
"""
|
|
1058
1066
|
self._show_info(self.get_tick_info, "tick", symbol=symbol)
|
|
1059
1067
|
|
|
1060
|
-
def
|
|
1068
|
+
def get_rate_info(self, symbol: str, timeframe: str = "1m") -> RateInfo | None:
|
|
1069
|
+
"""Get the most recent bar for a specified symbol and timeframe.
|
|
1070
|
+
|
|
1071
|
+
Args:
|
|
1072
|
+
symbol (str): The symbol for which to get the rate information.
|
|
1073
|
+
timeframe (str): The timeframe for the rate information. Default is '1m'.
|
|
1074
|
+
See ``bbstrader.metatrader.utils.TIMEFRAMES`` for supported timeframes.
|
|
1075
|
+
Returns:
|
|
1076
|
+
RateInfo: The most recent bar as a RateInfo named tuple.
|
|
1077
|
+
None: If no rates are found or an error occurs.
|
|
1078
|
+
Raises:
|
|
1079
|
+
MT5TerminalError: A specific exception based on the error code.
|
|
1080
|
+
"""
|
|
1081
|
+
rates = mt5.copy_rates_from_pos(symbol, TIMEFRAMES[timeframe], 0, 1)
|
|
1082
|
+
if rates is None or len(rates) == 0:
|
|
1083
|
+
return None
|
|
1084
|
+
rate = rates[0]
|
|
1085
|
+
return RateInfo(*rate)
|
|
1086
|
+
|
|
1087
|
+
def get_rates_from_pos(
|
|
1088
|
+
self, symbol: str, timeframe: str, start_pos: int = 0, bars: int = 1
|
|
1089
|
+
) -> NDArray[np.void]:
|
|
1090
|
+
"""
|
|
1091
|
+
Get bars from the MetaTrader 5 terminal starting from the specified index.
|
|
1092
|
+
|
|
1093
|
+
Args:
|
|
1094
|
+
symbol: Financial instrument name, for example, "EURUSD"
|
|
1095
|
+
timeframe: Timeframe the bars are requested for.
|
|
1096
|
+
start_pos: Initial index of the bar the data are requested from.
|
|
1097
|
+
bars: Number of bars to receive.
|
|
1098
|
+
|
|
1099
|
+
Returns:
|
|
1100
|
+
bars as the numpy array with the named time, open, high, low, close, tick_volume, spread and real_volume columns.
|
|
1101
|
+
Returns an empty array in case of an error.
|
|
1102
|
+
"""
|
|
1103
|
+
rates = mt5.copy_rates_from_pos(symbol, TIMEFRAMES[timeframe], start_pos, bars)
|
|
1104
|
+
if rates is None or len(rates) == 0:
|
|
1105
|
+
return np.array([], dtype=RateDtype)
|
|
1106
|
+
return rates
|
|
1107
|
+
|
|
1108
|
+
def get_rates_from_date(
|
|
1109
|
+
self,
|
|
1110
|
+
symbol: str,
|
|
1111
|
+
timeframe: str,
|
|
1112
|
+
date_from: datetime | pd.Timestamp,
|
|
1113
|
+
bars: int = 1,
|
|
1114
|
+
) -> NDArray[np.void]:
|
|
1115
|
+
"""
|
|
1116
|
+
Get bars from the MetaTrader 5 terminal starting from the specified date.
|
|
1117
|
+
|
|
1118
|
+
Args:
|
|
1119
|
+
symbol: Financial instrument name, for example, "EURUSD"
|
|
1120
|
+
timeframe: Timeframe the bars are requested for.
|
|
1121
|
+
date_from: Date of opening of the first bar from the requested sample.
|
|
1122
|
+
bars: Number of bars to receive.
|
|
1123
|
+
|
|
1124
|
+
Returns:
|
|
1125
|
+
bars as the numpy array with the named time, open, high, low, close, tick_volume, spread and real_volume columns.
|
|
1126
|
+
Returns an empty array in case of an error.
|
|
1127
|
+
|
|
1128
|
+
"""
|
|
1129
|
+
rates = mt5.copy_rates_from(symbol, TIMEFRAMES[timeframe], date_from, bars)
|
|
1130
|
+
if rates is None or len(rates) == 0:
|
|
1131
|
+
return np.array([], dtype=RateDtype)
|
|
1132
|
+
return rates
|
|
1133
|
+
|
|
1134
|
+
def get_rates_range(
|
|
1135
|
+
self,
|
|
1136
|
+
symbol: str,
|
|
1137
|
+
timeframe: str,
|
|
1138
|
+
date_from: datetime | pd.Timestamp,
|
|
1139
|
+
date_to: datetime | pd.Timestamp = datetime.now(),
|
|
1140
|
+
) -> NDArray[np.void]:
|
|
1141
|
+
"""
|
|
1142
|
+
Get bars in the specified date range from the MetaTrader 5 terminal.
|
|
1143
|
+
|
|
1144
|
+
Args:
|
|
1145
|
+
symbol: Financial instrument name, for example, "EURUSD"
|
|
1146
|
+
timeframe: Timeframe the bars are requested for.
|
|
1147
|
+
date_from: Date the bars are requested from.
|
|
1148
|
+
date_to: Date, up to which the bars are requested.
|
|
1149
|
+
|
|
1150
|
+
Returns:
|
|
1151
|
+
bars as the numpy array with the named time, open, high, low, close, tick_volume, spread and real_volume columns.
|
|
1152
|
+
Returns an empty array in case of an error.
|
|
1153
|
+
"""
|
|
1154
|
+
rates = mt5.copy_rates_range(symbol, TIMEFRAMES[timeframe], date_from, date_to)
|
|
1155
|
+
if rates is None or len(rates) == 0:
|
|
1156
|
+
return np.array([], dtype=RateDtype)
|
|
1157
|
+
return rates
|
|
1158
|
+
|
|
1159
|
+
def get_tick_from_date(
|
|
1160
|
+
self,
|
|
1161
|
+
symbol: str,
|
|
1162
|
+
date_from: datetime | pd.Timestamp,
|
|
1163
|
+
ticks: int = 1,
|
|
1164
|
+
flag: Literal["all", "info", "trade"] = "all",
|
|
1165
|
+
) -> NDArray[np.void]:
|
|
1166
|
+
"""
|
|
1167
|
+
Get ticks from the MetaTrader 5 terminal starting from the specified date.
|
|
1168
|
+
|
|
1169
|
+
Args:
|
|
1170
|
+
symbol: Financial instrument name, for example, "EURUSD"
|
|
1171
|
+
date_from: Date the ticks are requested from.
|
|
1172
|
+
ticks: Number of bars to receive.
|
|
1173
|
+
flag: A flag to define the type of the requested ticks ("all", "info", "trade").
|
|
1174
|
+
|
|
1175
|
+
Returns:
|
|
1176
|
+
Returns ticks as the numpy array with the named time, bid, ask, last and flags columns.
|
|
1177
|
+
Return an empty array in case of an error.
|
|
1178
|
+
"""
|
|
1179
|
+
ticks_data = mt5.copy_ticks_from(symbol, date_from, ticks, TickFlag[flag])
|
|
1180
|
+
if ticks_data is None or len(ticks_data) == 0:
|
|
1181
|
+
return np.array([], dtype=TickDtype)
|
|
1182
|
+
return ticks_data
|
|
1183
|
+
|
|
1184
|
+
def get_tick_range(
|
|
1185
|
+
self,
|
|
1186
|
+
symbol: str,
|
|
1187
|
+
date_from: datetime | pd.Timestamp,
|
|
1188
|
+
date_to: datetime | pd.Timestamp = datetime.now(),
|
|
1189
|
+
flag: Literal["all", "info", "trade"] = "all",
|
|
1190
|
+
) -> NDArray[np.void]:
|
|
1191
|
+
"""
|
|
1192
|
+
Get ticks for the specified date range from the MetaTrader 5 terminal.
|
|
1193
|
+
|
|
1194
|
+
Args:
|
|
1195
|
+
symbol: Financial instrument name, for example, "EURUSD"
|
|
1196
|
+
date_from: Date the ticks are requested from.
|
|
1197
|
+
date_to: Date, up to which the ticks are requested.
|
|
1198
|
+
flag: A flag to define the type of the requested ticks ("all", "info", "trade").
|
|
1199
|
+
|
|
1200
|
+
Returns:
|
|
1201
|
+
Returns ticks as the numpy array with the named time, bid, ask, last and flags columns.
|
|
1202
|
+
Return an empty array in case of an error.
|
|
1203
|
+
"""
|
|
1204
|
+
ticks_data = mt5.copy_ticks_range(symbol, date_from, date_to, TickFlag[flag])
|
|
1205
|
+
if ticks_data is None or len(ticks_data) == 0:
|
|
1206
|
+
return np.array([], dtype=TickDtype)
|
|
1207
|
+
return ticks_data
|
|
1208
|
+
|
|
1209
|
+
def get_market_book(self, symbol: str) -> Tuple[BookInfo]:
|
|
1061
1210
|
"""
|
|
1062
1211
|
Get the Market Depth content for a specific symbol.
|
|
1063
1212
|
Args:
|
|
@@ -1199,7 +1348,7 @@ class Account(object):
|
|
|
1199
1348
|
group: Optional[str] = None,
|
|
1200
1349
|
ticket: Optional[int] = None,
|
|
1201
1350
|
to_df: bool = False,
|
|
1202
|
-
) -> Union[pd.DataFrame, Tuple[TradePosition]
|
|
1351
|
+
) -> Union[pd.DataFrame, Tuple[TradePosition]]:
|
|
1203
1352
|
"""
|
|
1204
1353
|
Get open positions with the ability to filter by symbol or ticket.
|
|
1205
1354
|
There are four call options:
|
|
@@ -1229,7 +1378,6 @@ class Account(object):
|
|
|
1229
1378
|
Returns:
|
|
1230
1379
|
Union[pd.DataFrame, Tuple[TradePosition], None]:
|
|
1231
1380
|
- `TradePosition` in the form of a named tuple structure (namedtuple) or pd.DataFrame.
|
|
1232
|
-
- `None` in case of an error.
|
|
1233
1381
|
|
|
1234
1382
|
Notes:
|
|
1235
1383
|
The method allows receiving all open positions within a specified period.
|
|
@@ -1285,7 +1433,7 @@ class Account(object):
|
|
|
1285
1433
|
position: Optional[int] = None, # TradePosition.ticket
|
|
1286
1434
|
to_df: bool = True,
|
|
1287
1435
|
save: bool = False,
|
|
1288
|
-
) -> Union[pd.DataFrame, Tuple[TradeDeal]
|
|
1436
|
+
) -> Union[pd.DataFrame, Tuple[TradeDeal]]:
|
|
1289
1437
|
"""
|
|
1290
1438
|
Get deals from trading history within the specified interval
|
|
1291
1439
|
with the ability to filter by `ticket` or `position`.
|
|
@@ -1323,7 +1471,6 @@ class Account(object):
|
|
|
1323
1471
|
Returns:
|
|
1324
1472
|
Union[pd.DataFrame, Tuple[TradeDeal], None]:
|
|
1325
1473
|
- `TradeDeal` in the form of a named tuple structure (namedtuple) or pd.DataFrame().
|
|
1326
|
-
- `None` in case of an error.
|
|
1327
1474
|
|
|
1328
1475
|
Notes:
|
|
1329
1476
|
The method allows receiving all history orders within a specified period.
|
|
@@ -1413,7 +1560,6 @@ class Account(object):
|
|
|
1413
1560
|
Returns:
|
|
1414
1561
|
Union[pd.DataFrame, Tuple[TradeOrder], None]:
|
|
1415
1562
|
- `TradeOrder` in the form of a named tuple structure (namedtuple) or pd.DataFrame().
|
|
1416
|
-
- `None` in case of an error.
|
|
1417
1563
|
|
|
1418
1564
|
Notes:
|
|
1419
1565
|
The method allows receiving all history orders within a specified period.
|
|
@@ -1478,7 +1624,7 @@ class Account(object):
|
|
|
1478
1624
|
position: Optional[int] = None, # position ticket
|
|
1479
1625
|
to_df: bool = True,
|
|
1480
1626
|
save: bool = False,
|
|
1481
|
-
) -> Union[pd.DataFrame, Tuple[TradeOrder]
|
|
1627
|
+
) -> Union[pd.DataFrame, Tuple[TradeOrder]]:
|
|
1482
1628
|
"""
|
|
1483
1629
|
Get orders from trading history within the specified interval
|
|
1484
1630
|
with the ability to filter by `ticket` or `position`.
|
|
@@ -1516,7 +1662,6 @@ class Account(object):
|
|
|
1516
1662
|
Returns:
|
|
1517
1663
|
Union[pd.DataFrame, Tuple[TradeOrder], None]
|
|
1518
1664
|
- `TradeOrder` in the form of a named tuple structure (namedtuple) or pd.DataFrame().
|
|
1519
|
-
- `None` in case of an error.
|
|
1520
1665
|
|
|
1521
1666
|
Notes:
|
|
1522
1667
|
The method allows receiving all history orders within a specified period.
|
|
@@ -1597,16 +1742,11 @@ class Account(object):
|
|
|
1597
1742
|
Returns:
|
|
1598
1743
|
List[TradeDeal]: List of today deals
|
|
1599
1744
|
"""
|
|
1600
|
-
|
|
1601
|
-
history = (
|
|
1602
|
-
self.get_trades_history(date_from=date_from, group=group, to_df=False) or []
|
|
1603
|
-
)
|
|
1745
|
+
history = self.get_trades_history(group=group, to_df=False) or []
|
|
1604
1746
|
positions_ids = set([deal.position_id for deal in history if deal.magic == id])
|
|
1605
1747
|
today_deals = []
|
|
1606
1748
|
for position in positions_ids:
|
|
1607
|
-
deal = self.get_trades_history(
|
|
1608
|
-
date_from=date_from, position=position, to_df=False
|
|
1609
|
-
)
|
|
1749
|
+
deal = self.get_trades_history(position=position, to_df=False) or []
|
|
1610
1750
|
if deal is not None and len(deal) == 2:
|
|
1611
1751
|
deal_time = datetime.fromtimestamp(deal[1].time)
|
|
1612
1752
|
if deal_time.date() == datetime.now().date():
|