bbstrader 0.1.8__py3-none-any.whl → 0.1.91__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.

@@ -3,13 +3,66 @@ import MetaTrader5 as Mt5
3
3
  from datetime import datetime
4
4
  from typing import Union, Optional
5
5
  from bbstrader.metatrader.utils import (
6
- raise_mt5_error, TimeFrame, TIMEFRAMES)
7
- from bbstrader.metatrader.account import INIT_MSG
6
+ raise_mt5_error,
7
+ TimeFrame,
8
+ TIMEFRAMES
9
+ )
10
+ from bbstrader.metatrader.account import Account
11
+ from bbstrader.metatrader.account import AMG_EXCHANGES
12
+ from bbstrader.metatrader.account import check_mt5_connection
8
13
  from pandas.tseries.offsets import CustomBusinessDay
9
14
  from pandas.tseries.holiday import USFederalHolidayCalendar
15
+ from exchange_calendars import(
16
+ get_calendar,
17
+ get_calendar_names
18
+ )
19
+
20
+ __all__ = [
21
+ 'Rates',
22
+ 'download_historical_data',
23
+ 'get_data_from_pos'
24
+ ]
10
25
 
11
26
  MAX_BARS = 10_000_000
12
27
 
28
+ IDX_CALENDARS = {
29
+ "CAD": "XTSE",
30
+ "AUD": "XASX",
31
+ "GBP": "XLON",
32
+ "HKD": "XSHG",
33
+ "ZAR": "XJSE",
34
+ "CHF": "XSWX",
35
+ "NOK": "XOSL",
36
+ "EUR": "XETR",
37
+ "SGD": "XSES",
38
+ "USD": "us_futures",
39
+ "JPY": "us_futures",
40
+ }
41
+
42
+ COMD_CALENDARS = {
43
+ "Energies" : "us_futures",
44
+ "Metals" : "us_futures",
45
+ "Agricultures" : "CBOT",
46
+ "Bonds": {"USD" : "CBOT", "EUR": "EUREX"},
47
+ }
48
+
49
+ CALENDARS = {
50
+ "FX" : "us_futures",
51
+ "STK" : AMG_EXCHANGES,
52
+ "ETF" : AMG_EXCHANGES,
53
+ "IDX" : IDX_CALENDARS,
54
+ "COMD" : COMD_CALENDARS,
55
+ "CRYPTO": "24/7",
56
+ "FUT" : None,
57
+ }
58
+
59
+ SESSION_TIMEFRAMES = [
60
+ Mt5.TIMEFRAME_D1,
61
+ Mt5.TIMEFRAME_W1,
62
+ Mt5.TIMEFRAME_H12,
63
+ Mt5.TIMEFRAME_MN1
64
+ ]
65
+
13
66
 
14
67
  class Rates(object):
15
68
  """
@@ -26,8 +79,8 @@ class Rates(object):
26
79
  or just set it to Unlimited.
27
80
  In your MT5 terminal, go to `Tools` -> `Options` -> `Charts` -> `Max bars in chart`.
28
81
 
29
- 2. The `get_open, get_high, get_low, get_close, get_adj_close, get_returns,
30
- get_volume` properties returns data in Broker's timezone.
82
+ 2. The `open, high, low, close, adjclose, returns,
83
+ volume` properties returns data in Broker's timezone by default.
31
84
 
32
85
  Example:
33
86
  >>> rates = Rates("EURUSD", "1h")
@@ -70,13 +123,11 @@ class Rates(object):
70
123
  self.start_pos = self._get_start_pos(start_pos, time_frame)
71
124
  self.count = count
72
125
  self._mt5_initialized()
126
+ self.__account = Account()
73
127
  self.__data = self.get_rates_from_pos()
74
128
 
75
-
76
129
  def _mt5_initialized(self):
77
- """Ensures the MetaTrader 5 Terminal is initialized."""
78
- if not Mt5.initialize():
79
- raise_mt5_error(message=INIT_MSG)
130
+ check_mt5_connection()
80
131
 
81
132
  def _get_start_pos(self, index, time_frame):
82
133
  if isinstance(index, int):
@@ -127,8 +178,8 @@ class Rates(object):
127
178
  return TIMEFRAMES[time_frame]
128
179
 
129
180
  def _fetch_data(
130
- self, start: Union[int, datetime],
131
- count: Union[int, datetime]
181
+ self, start: Union[int, datetime , pd.Timestamp],
182
+ count: Union[int, datetime, pd.Timestamp], lower_colnames=False, utc=False,
132
183
  ) -> Union[pd.DataFrame, None]:
133
184
  """Fetches data from MT5 and returns a DataFrame or None."""
134
185
  try:
@@ -136,7 +187,10 @@ class Rates(object):
136
187
  rates = Mt5.copy_rates_from_pos(
137
188
  self.symbol, self.time_frame, start, count
138
189
  )
139
- elif isinstance(start, datetime) and isinstance(count, datetime):
190
+ elif (
191
+ isinstance(start, (datetime, pd.Timestamp)) and
192
+ isinstance(count, (datetime, pd.Timestamp))
193
+ ):
140
194
  rates = Mt5.copy_rates_range(
141
195
  self.symbol, self.time_frame, start, count
142
196
  )
@@ -144,28 +198,103 @@ class Rates(object):
144
198
  return None
145
199
 
146
200
  df = pd.DataFrame(rates)
147
- return self._format_dataframe(df)
201
+ return self._format_dataframe(df, lower_colnames=lower_colnames, utc=utc)
148
202
  except Exception as e:
149
203
  raise_mt5_error(e)
150
204
 
151
- def _format_dataframe(self, df: pd.DataFrame) -> pd.DataFrame:
205
+ def _format_dataframe(self, df: pd.DataFrame,
206
+ lower_colnames=False, utc=False) -> pd.DataFrame:
152
207
  """Formats the raw MT5 data into a standardized DataFrame."""
153
208
  df = df.copy()
154
209
  df = df[['time', 'open', 'high', 'low', 'close', 'tick_volume']]
155
210
  df.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
156
211
  df['Adj Close'] = df['Close']
157
212
  df = df[['Date', 'Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume']]
158
- df['Date'] = pd.to_datetime(df['Date'], unit='s')
213
+ #df = df.columns.rename(str.lower).str.replace(' ', '_')
214
+ df['Date'] = pd.to_datetime(df['Date'], unit='s', utc=utc)
159
215
  df.set_index('Date', inplace=True)
216
+ if lower_colnames:
217
+ df.columns = df.columns.str.lower().str.replace(' ', '_')
218
+ df.index.name = df.index.name.lower().replace(' ', '_')
160
219
  return df
161
220
 
162
- def get_rates_from_pos(self) -> Union[pd.DataFrame, None]:
221
+ def _filter_data(self, df: pd.DataFrame, date_from=None, date_to=None, fill_na=False) -> pd.DataFrame:
222
+ df = df.copy()
223
+ symbol_type = self.__account.get_symbol_type(self.symbol)
224
+ currencies = self.__account.get_currency_rates(self.symbol)
225
+ s_info = self.__account.get_symbol_info(self.symbol)
226
+ if symbol_type in CALENDARS:
227
+ if symbol_type == 'STK' or symbol_type == 'ETF':
228
+ for exchange in CALENDARS[symbol_type]:
229
+ if exchange in get_calendar_names():
230
+ symbols = self.__account.get_stocks_from_exchange(
231
+ exchange_code=exchange)
232
+ if self.symbol in symbols:
233
+ calendar = get_calendar(exchange, side='right')
234
+ break
235
+ elif symbol_type == 'IDX':
236
+ calendar = get_calendar(CALENDARS[symbol_type][currencies['mc']], side='right')
237
+ elif symbol_type == 'COMD':
238
+ for commodity in CALENDARS[symbol_type]:
239
+ if commodity in s_info.path:
240
+ calendar = get_calendar(CALENDARS[symbol_type][commodity], side='right')
241
+ elif symbol_type == 'FUT':
242
+ if 'Index' in s_info.path:
243
+ calendar = get_calendar(CALENDARS['IDX'][currencies['mc']], side='right')
244
+ else:
245
+ for commodity, cal in COMD_CALENDARS.items():
246
+ if self.symbol in self.__account.get_future_symbols(category=commodity):
247
+ if commodity == 'Bonds':
248
+ calendar = get_calendar(cal[currencies['mc']], side='right')
249
+ else:
250
+ calendar = get_calendar(cal, side='right')
251
+ else:
252
+ calendar = get_calendar(CALENDARS[symbol_type], side='right')
253
+ date_from = date_from or df.index[0]
254
+ date_to = date_to or df.index[-1]
255
+ if self.time_frame in SESSION_TIMEFRAMES:
256
+ valid_sessions = calendar.sessions_in_range(date_from, date_to)
257
+ else:
258
+ valid_sessions = calendar.minutes_in_range(date_from, date_to)
259
+ if self.time_frame in [Mt5.TIMEFRAME_M1, Mt5.TIMEFRAME_D1]:
260
+ # save the index name of the dataframe
261
+ index_name = df.index.name
262
+ if fill_na:
263
+ if isinstance(fill_na, bool):
264
+ method = 'nearest'
265
+ if isinstance(fill_na, str):
266
+ method = fill_na
267
+ df = df.reindex(valid_sessions, method=method)
268
+ else:
269
+ df.reindex(valid_sessions, method=None)
270
+ df.index = df.index.rename(index_name)
271
+ else:
272
+ df = df[df.index.isin(valid_sessions)]
273
+ return df
274
+
275
+ def _check_filter(self, filter, utc):
276
+ if filter and self.time_frame not in SESSION_TIMEFRAMES and not utc:
277
+ utc = True
278
+ elif filter and self.time_frame in SESSION_TIMEFRAMES and utc:
279
+ utc = False
280
+ return utc
281
+
282
+ def get_rates_from_pos(self, filter=False, fill_na=False,
283
+ lower_colnames=False, utc=False
284
+ ) -> Union[pd.DataFrame, None]:
163
285
  """
164
286
  Retrieves historical data starting from a specific position.
165
287
 
166
288
  Uses the `start_pos` and `count` attributes specified during
167
289
  initialization to fetch data.
168
290
 
291
+ Args:
292
+ filter : See `Rates.get_historical_data` for more details.
293
+ fill_na : See `Rates.get_historical_data` for more details.
294
+ lower_colnames : If True, the column names will be converted to lowercase.
295
+ utc (bool, optional): If True, the data will be in UTC timezone.
296
+ Defaults to False.
297
+
169
298
  Returns:
170
299
  Union[pd.DataFrame, None]: A DataFrame containing historical
171
300
  data if successful, otherwise None.
@@ -182,31 +311,37 @@ class Rates(object):
182
311
  "Both 'start_pos' and 'count' must be provided "
183
312
  "when calling 'get_rates_from_pos'."
184
313
  )
185
- df = self._fetch_data(self.start_pos, self.count)
314
+ utc = self._check_filter(filter, utc)
315
+ df = self._fetch_data(self.start_pos, self.count,
316
+ lower_colnames=lower_colnames, utc=utc)
317
+ if df is None:
318
+ return None
319
+ if filter:
320
+ return self._filter_data(df, fill_na=fill_na)
186
321
  return df
187
322
 
188
323
  @property
189
- def get_open(self):
324
+ def open(self):
190
325
  return self.__data['Open']
191
326
 
192
327
  @property
193
- def get_high(self):
328
+ def high(self):
194
329
  return self.__data['High']
195
330
 
196
331
  @property
197
- def get_low(self):
332
+ def low(self):
198
333
  return self.__data['Low']
199
334
 
200
335
  @property
201
- def get_close(self):
336
+ def close(self):
202
337
  return self.__data['Close']
203
338
 
204
339
  @property
205
- def get_adj_close(self):
340
+ def adjclose(self):
206
341
  return self.__data['Adj Close']
207
342
 
208
343
  @property
209
- def get_returns(self):
344
+ def returns(self):
210
345
  """
211
346
  Fractional change between the current and a prior element.
212
347
 
@@ -224,23 +359,52 @@ class Rates(object):
224
359
  return data['Returns']
225
360
 
226
361
  @property
227
- def get_volume(self):
362
+ def volume(self):
228
363
  return self.__data['Volume']
229
364
 
230
365
  def get_historical_data(
231
366
  self,
232
- date_from: datetime,
233
- date_to: datetime = datetime.now(),
367
+ date_from: datetime | pd.Timestamp,
368
+ date_to: datetime | pd.Timestamp = pd.Timestamp.now(),
369
+ utc: bool = False,
370
+ filter: Optional[bool] = False,
371
+ fill_na: Optional[bool | str] = False,
372
+ lower_colnames: Optional[bool] = True,
234
373
  save_csv: Optional[bool] = False,
235
374
  ) -> Union[pd.DataFrame, None]:
236
375
  """
237
376
  Retrieves historical data within a specified date range.
238
377
 
239
378
  Args:
240
- date_from (datetime): Starting date for data retrieval.
241
- date_to (datetime, optional): Ending date for data retrieval.
379
+ date_from : Starting date for data retrieval.
380
+
381
+ date_to : Ending date for data retrieval.
242
382
  Defaults to the current time.
243
- save_csv (str, optional): File path to save the data as a CSV.
383
+
384
+ utc : If True, the data will be in UTC timezone.
385
+ Defaults to False.
386
+
387
+ filter : If True, the data will be filtered based
388
+ on the trading sessions for the symbol.
389
+ This is use when we want to use the data for backtesting using Zipline.
390
+
391
+ fill_na : If True, the data will be filled with the nearest value.
392
+ This is use only when `filter` is True and time frame is "1m" or "D1",
393
+ this is because we use ``calendar.minutes_in_range`` or ``calendar.sessions_in_range``
394
+ where calendar is the ``ExchangeCalendar`` from `exchange_calendars` package.
395
+ So, for "1m" or "D1" time frame, the data will be filled with the nearest value
396
+ because the data from MT5 will have approximately the same number of rows as the
397
+ number of trading days or minute in the exchange calendar, so we can fill the missing
398
+ data with the nearest value.
399
+
400
+ But for other time frames, the data will be reindexed with the exchange calendar
401
+ because the data from MT5 will have more rows than the number of trading days or minute
402
+ in the exchange calendar. So we only take the data that is in the range of the exchange
403
+ calendar sessions or minutes.
404
+
405
+ lower_colnames : If True, the column names will be converted to lowercase.
406
+
407
+ save_csv : File path to save the data as a CSV.
244
408
  If None, the data won't be saved.
245
409
 
246
410
  Returns:
@@ -251,9 +415,48 @@ class Rates(object):
251
415
  ValueError: If the starting date is greater than the ending date.
252
416
 
253
417
  Notes:
254
- The Datetime for this method is in Local timezone.
418
+ The `filter` for this method can be use only for Admira Markets Group (AMG) symbols.
419
+ The Datetime for this method is in Local timezone by default.
420
+ All STK symbols are filtered based on the the exchange calendar.
421
+ All FX symbols are filtered based on the ``us_futures`` calendar.
422
+ All IDX symbols are filtered based on the exchange calendar of margin currency.
423
+ All COMD symbols are filtered based on the exchange calendar of the commodity.
255
424
  """
256
- df = self._fetch_data(date_from, date_to)
257
- if save_csv and df is not None:
425
+ utc = self._check_filter(filter, utc)
426
+ df = self._fetch_data(date_from, date_to,
427
+ lower_colnames=lower_colnames, utc=utc)
428
+ if df is None:
429
+ return None
430
+ if filter:
431
+ df = self._filter_data(df, date_from=date_from, date_to=date_to, fill_na=fill_na)
432
+ if save_csv:
258
433
  df.to_csv(f"{self.symbol}.csv")
259
434
  return df
435
+
436
+ def download_historical_data(symbol, time_frame, date_from,
437
+ date_to=pd.Timestamp.now(),lower_colnames=True,
438
+ utc=False, filter=False, fill_na=False, save_csv=False):
439
+ """Download historical data from MetaTrader 5 terminal.
440
+ See `Rates.get_historical_data` for more details.
441
+ """
442
+ rates = Rates(symbol, time_frame)
443
+ data = rates.get_historical_data(
444
+ date_from=date_from,
445
+ date_to=date_to,
446
+ save_csv=save_csv,
447
+ utc=utc,
448
+ filter=filter,
449
+ lower_colnames=lower_colnames
450
+ )
451
+ return data
452
+
453
+ def get_data_from_pos(symbol, time_frame, start_pos=0, fill_na=False,
454
+ count=MAX_BARS, lower_colnames=False, utc=False, filter=False,
455
+ session_duration=23.0):
456
+ """Get historical data from a specific position.
457
+ See `Rates.get_rates_from_pos` for more details.
458
+ """
459
+ rates = Rates(symbol, time_frame, start_pos, count, session_duration)
460
+ data = rates.get_rates_from_pos(filter=filter, fill_na=fill_na,
461
+ lower_colnames=lower_colnames, utc=utc)
462
+ return data
@@ -7,8 +7,18 @@ import MetaTrader5 as Mt5
7
7
  from bbstrader.metatrader.account import Account
8
8
  from bbstrader.metatrader.rates import Rates
9
9
  from bbstrader.metatrader.utils import (
10
- TIMEFRAMES, raise_mt5_error, TimeFrame)
11
- from typing import List, Dict, Optional, Literal, Union, Any
10
+ TIMEFRAMES,
11
+ raise_mt5_error,
12
+ TimeFrame
13
+ )
14
+ from typing import (
15
+ List,
16
+ Dict,
17
+ Optional,
18
+ Literal,
19
+ Union,
20
+ Any
21
+ )
12
22
 
13
23
 
14
24
  _COMMD_SUPPORTED_ = [
@@ -16,7 +26,6 @@ _COMMD_SUPPORTED_ = [
16
26
  'XAGEUR', 'XAGUSD', 'XAUAUD', 'XAUEUR', 'XAUUSD', 'XAUGBP', 'USOIL'
17
27
  ]
18
28
 
19
-
20
29
  _ADMIRAL_MARKETS_FUTURES_ = [
21
30
  '#USTNote_', '#Bund_', '#USDX_', '_AUS200_', '_Canada60_', '_SouthAfrica40_',
22
31
  '_STXE600_', '_EURO50_', '_GER40_', '_GermanyTech30_', '_MidCapGER50_',
@@ -25,6 +34,7 @@ _ADMIRAL_MARKETS_FUTURES_ = [
25
34
  '_XAU_', '_HK50_', '_HSCEI50_'
26
35
  ]
27
36
 
37
+ __all__ = ['RiskManagement']
28
38
 
29
39
  class RiskManagement(Account):
30
40
  """
@@ -135,7 +145,7 @@ class RiskManagement(Account):
135
145
  self.pchange = pchange_sl
136
146
  self.var_level = var_level
137
147
  self.var_tf = var_time_frame
138
- self.daily_dd = daily_risk
148
+ self.daily_dd = round(daily_risk, 5)
139
149
  self.max_risk = max_risk
140
150
  self.rr = rr
141
151
  self.sl = sl
@@ -193,7 +203,7 @@ class RiskManagement(Account):
193
203
  volume_step = s_info.volume_step
194
204
  lot = self.currency_risk()['lot']
195
205
  steps = self._volume_step(volume_step)
196
- if steps >= 2:
206
+ if float(steps) >= float(1):
197
207
  return round(lot, steps)
198
208
  else:
199
209
  return round(lot)
@@ -203,13 +213,13 @@ class RiskManagement(Account):
203
213
 
204
214
  value_str = str(value)
205
215
 
206
- if '.' in value_str:
216
+ if '.' in value_str and value_str != '1.0':
207
217
  decimal_index = value_str.index('.')
208
218
  num_digits = len(value_str) - decimal_index - 1
209
-
210
219
  return num_digits
211
- elif value_str == '1':
212
- return 1
220
+
221
+ elif value_str == '1.0':
222
+ return 0
213
223
  else:
214
224
  return 0
215
225
 
@@ -254,7 +264,7 @@ class RiskManagement(Account):
254
264
  interval = round((minutes / tf_int) * 252)
255
265
 
256
266
  rate = Rates(self.symbol, self._tf, 0, interval)
257
- returns = rate.get_returns*100
267
+ returns = rate.returns*100
258
268
  std = returns.std()
259
269
  point = self.get_symbol_info(self.symbol).point
260
270
  av_price = (self.symbol_info.bid + self.symbol_info.ask)/2
@@ -308,7 +318,7 @@ class RiskManagement(Account):
308
318
  interval = round((minutes / tf_int) * 252)
309
319
 
310
320
  rate = Rates(self.symbol, tf, 0, interval)
311
- returns = rate.get_returns*100
321
+ returns = rate.returns*100
312
322
  p = self.get_account_info().margin_free
313
323
  mu = returns.mean()
314
324
  sigma = returns.std()
@@ -341,7 +351,7 @@ class RiskManagement(Account):
341
351
  """
342
352
  P = self.get_account_info().margin_free
343
353
  trade_risk = self.get_trade_risk()
344
- loss_allowed = P * trade_risk
354
+ loss_allowed = P * trade_risk / 100
345
355
  var = self.calculate_var(c=self.var_level, tf=self.var_tf)
346
356
  return min(var, loss_allowed)
347
357
 
@@ -405,10 +415,11 @@ class RiskManagement(Account):
405
415
 
406
416
  av_price = (s_info.bid + s_info.ask)/2
407
417
  trade_risk = self.get_trade_risk()
408
- FX = self.get_symbol_type(self.symbol) == 'FX'
409
- COMD = self.get_symbol_type(self.symbol) == 'COMD'
410
- FUT = self.get_symbol_type(self.symbol) == 'FUT'
411
- CRYPTO = self.get_symbol_type(self.symbol) == 'CRYPTO'
418
+ symbol_type = self.get_symbol_type(self.symbol)
419
+ FX = symbol_type == 'FX'
420
+ COMD = symbol_type == 'COMD'
421
+ FUT = symbol_type == 'FUT'
422
+ CRYPTO = symbol_type == 'CRYPTO'
412
423
  if COMD:
413
424
  supported = _COMMD_SUPPORTED_
414
425
  if self.symbol.split('.')[0] not in supported:
@@ -503,14 +514,14 @@ class RiskManagement(Account):
503
514
  trade_loss = (lot * contract_size) * tick_value_loss
504
515
  trade_profit = (lot * contract_size) * tick_value_profit
505
516
 
506
- if self.get_symbol_type(self.symbol) == 'IDX':
507
- rates = self.get_currency_rates(self.symbol)
508
- if rates['mc'] == rates['pc'] == 'JPY':
509
- lot = lot * contract_size
510
- lot = self._check_lot(lot)
511
- volume = round(lot * av_price * contract_size)
512
- if contract_size == 1:
513
- volume = round(lot * av_price)
517
+ # if self.get_symbol_type(self.symbol) == 'IDX':
518
+ # rates = self.get_currency_rates(self.symbol)
519
+ # if rates['mc'] == rates['pc'] == 'JPY':
520
+ # lot = lot * contract_size
521
+ # lot = self._check_lot(lot)
522
+ # volume = round(lot * av_price * contract_size)
523
+ # if contract_size == 1:
524
+ # volume = round(lot * av_price)
514
525
 
515
526
  return {
516
527
  'currency_risk': currency_risk,