bbstrader 0.0.1__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,965 @@
1
+ import time
2
+ import pandas as pd
3
+ import numpy as np
4
+ from datetime import datetime
5
+ from bbstrader.metatrader.rates import Rates
6
+ from bbstrader.metatrader.trade import Trade
7
+ from bbstrader.trading.utils import tf_mapping
8
+ from bbstrader.strategies import (
9
+ ArimaGarchStrategy, SMAStrategy, KLFStrategy, OrnsteinUhlenbeck,
10
+ )
11
+ from bbstrader.models import HMMRiskManager
12
+ from bbstrader.metatrader.utils import config_logger
13
+ from typing import Optional, Literal, List, Tuple
14
+
15
+ logger = config_logger(log_file='trade.log', console_log=False)
16
+
17
+ TRADING_DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
18
+ # ======== SMA TRADING ======================
19
+ def sma_trading(
20
+ trade: Trade,
21
+ tf: Optional[str] = '1h',
22
+ sma: Optional[int] = 35,
23
+ lma: Optional[int] = 80,
24
+ mm: Optional[bool] = True,
25
+ max_t: Optional[int] = 1,
26
+ iter_time: Optional[int |float] = 30,
27
+ risk_manager: str = 'hmm',
28
+ period: Literal['day', 'week', 'month'] = 'week',
29
+ **kwargs
30
+ ):
31
+ """
32
+ Executes a Simple Moving Average (SMA) trading strategy
33
+ with optional risk management using Hidden Markov Models (HMM).
34
+
35
+ Parameters
36
+ ==========
37
+ trade : Trade
38
+ The Trade object that encapsulates trading operations like
39
+ opening, closing positions, etc.
40
+ tf : str, optional
41
+ Time frame for the trading strategy, defaults to '1h' (1 hour).
42
+ sma : int, optional
43
+ Short Moving Average period, defaults to 35.
44
+ lma : int, optional
45
+ Long Moving Average period, defaults to 80.
46
+ mm : bool, optional
47
+ Money management flag to enable/disable money management, defaults to True.
48
+ max_t : int, optional
49
+ Maximum number of trades allowed, defaults to 1.
50
+ iter_time : Union[int, float], optional
51
+ Iteration time for the trading loop, defaults to 30 seconds.
52
+ risk_manager : str
53
+ Specifies the risk management strategy to use,
54
+ 'hmm' for Hidden Markov Model.
55
+ period : Literal['day', 'week', 'month'], optional
56
+ Trading period to reset statistics and close positions,
57
+ can be 'day', 'week', or 'month', defaults to 'week'.
58
+ **kwargs
59
+ Additional keyword arguments for the HMM risk manager.
60
+
61
+ Returns
62
+ =======
63
+ None
64
+
65
+ Notes
66
+ =====
67
+ This function integrates a trading strategy based on simple moving averages
68
+ with an optional risk management layer using HMM.
69
+ It periodically checks for trading signals and executes buy or sell orders
70
+ based on the strategy signals and risk management conditions.
71
+ The trading period (day, week, month) determines when to reset statistics
72
+ and close all positions.
73
+
74
+ This function includes an infinite loop with time delays designed
75
+ to run continuously during market hours. Ensure proper exception handling
76
+ and resource management when integrating into a live trading environment.
77
+ """
78
+
79
+ def check(buys: list, sells: list):
80
+ if buys is not None or sells is not None:
81
+ logger.info(f"Checking for Break even SYMBOL={trade.symbol}...")
82
+ trade.break_even()
83
+
84
+ time_frame_mapping = tf_mapping()
85
+ if tf == 'D1':
86
+ trade_time = trade.get_minutes()
87
+ else:
88
+ trade_time = time_frame_mapping[tf]
89
+
90
+ rate = Rates(trade.symbol, tf, 0)
91
+ data = rate.get_rates_from_pos()
92
+ strategy = SMAStrategy(short_window=sma, long_window=lma)
93
+ hmm = HMMRiskManager(data=data, verbose=True,
94
+ iterations=1000, **kwargs)
95
+ time_intervals = 0
96
+ long_market = False
97
+ short_market = False
98
+ num_days = 0
99
+ logger.info(
100
+ f'Running SMA Strategy on {trade.symbol} in {tf} Interval ...\n')
101
+ while True:
102
+ current_date = datetime.now()
103
+ today = current_date.strftime("%A")
104
+ try:
105
+ buys = trade.get_current_buys()
106
+ if buys is not None:
107
+ logger.info(
108
+ f"Current buy positions SYMBOL={trade.symbol}: {buys}, STRATEGY=SMA")
109
+ sells = trade.get_current_sells()
110
+ if sells is not None:
111
+ logger.info(
112
+ f"Current sell positions SYMBOL={trade.symbol}: {sells}, STRATEGY=SMA")
113
+ long_market = buys is not None and len(buys) >= max_t
114
+ short_market = sells is not None and len(sells) >= max_t
115
+
116
+ time.sleep(0.5)
117
+ sig_rate = Rates(trade.symbol, tf, 0, lma)
118
+ hmm_data = sig_rate.get_returns.values
119
+ current_regime = hmm.which_trade_allowed(hmm_data)
120
+ logger.info(f'CURRENT REGIME = {current_regime}, SYMBOL={trade.symbol}, STRATEGY=SMA')
121
+ ma_data = sig_rate.get_close.values
122
+ signal = strategy.calculate_signals(ma_data)
123
+ logger.info(f"Calculating signal...SYMBOL={trade.symbol}, STRATEGY=SMA")
124
+ comment = f"{trade.expert_name}@{trade.version}"
125
+ if trade.trading_time() and today in TRADING_DAYS:
126
+ if signal is not None:
127
+ logger.info(f"SIGNAL = {signal}, SYMBOL={trade.symbol}, STRATEGY=SMA")
128
+ if signal == "EXIT" and short_market:
129
+ trade.close_positions(position_type='sell')
130
+ short_market = False
131
+ elif signal == "EXIT" and long_market:
132
+ trade.close_positions(position_type='buy')
133
+ long_market = False
134
+
135
+ if current_regime == 'LONG':
136
+ if signal == "LONG" and not long_market:
137
+ if time_intervals % trade_time == 0 or buys is None:
138
+ logger.info(f"Sending buy Order .... SYMBOL={trade.symbol}, STRATEGY=SMA")
139
+ trade.open_buy_position(mm=mm, comment=comment)
140
+ else:
141
+ check(buys, sells)
142
+ elif signal == "LONG" and long_market:
143
+ logger.info(f"Sorry Risk not allowed !!! SYMBOL={trade.symbol}, STRATEGY=SMA")
144
+ check(buys, sells)
145
+
146
+ elif current_regime == 'SHORT':
147
+ if signal == "SHORT" and not short_market:
148
+ if time_intervals % trade_time == 0 or sells is None:
149
+ logger.info(f"Sending Sell Order .... SYMBOL={trade.symbol}, STRATEGY=SMA")
150
+ trade.open_sell_position(
151
+ mm=mm, comment=comment)
152
+ else:
153
+ check(buys, sells)
154
+ elif signal == "SHORT" and short_market:
155
+ logger.info(f"Sorry Risk not Allowed !!! SYMBOL={trade.symbol}, STRATEGY=SMA")
156
+ check(buys, sells)
157
+ else:
158
+ logger.info(f"There is no signal !! SYMBOL={trade.symbol}, STRATEGY=SMA")
159
+ check(buys, sells)
160
+ else:
161
+ logger.info(f"Sorry It is Not trading Time !!! SYMBOL={trade.symbol}, STRATEGY=SMA")
162
+ check(buys, sells)
163
+ except Exception as e:
164
+ logger.error(f"{e}, SYMBOL={trade.symbol}, STRATEGY=SMA")
165
+ time.sleep((60 * iter_time) - 1.5)
166
+ if iter_time == 1:
167
+ time_intervals += 1
168
+ elif iter_time == trade_time:
169
+ time_intervals += trade_time
170
+ else:
171
+ time_intervals += (trade_time/iter_time)
172
+ if period.lower() == 'month':
173
+ if trade.days_end() and today != 'Friday':
174
+ sleep_time = trade.sleep_time()
175
+ logger.info(f"End of the Day !!! SYMBOL={trade.symbol}, STRATEGY=SMA")
176
+ time.sleep(60 * sleep_time)
177
+ num_days += 1
178
+
179
+ elif trade.days_end() and today == 'Friday':
180
+ logger.info(f"End of the Week !!! SYMBOL={trade.symbol}, STRATEGY=SMA")
181
+ sleep_time = trade.sleep_time(weekend=True)
182
+ time.sleep(60 * sleep_time)
183
+ num_days += 1
184
+
185
+ elif (
186
+ trade.days_end()
187
+ and today == 'Friday'
188
+ and num_days >= 20
189
+ ):
190
+ trade.close_positions(position_type='all', comment=comment)
191
+ logger.info(f"End of the Month !!! SYMBOL={trade.symbol}, STRATEGY=SMA")
192
+ trade.statistics(save=True)
193
+ break
194
+
195
+ elif period.lower() == 'week':
196
+ if trade.days_end() and today != 'Friday':
197
+ sleep_time = trade.sleep_time()
198
+ time.sleep(60 * sleep_time)
199
+
200
+ elif trade.days_end() and today == 'Friday':
201
+ trade.close_positions(position_type='all', comment=comment)
202
+ logger.info(f"End of the Week !!! SYMBOL={trade.symbol}, STRATEGY=SMA")
203
+ trade.statistics(save=True)
204
+ break
205
+
206
+ elif period.lower() == 'day':
207
+ if trade.days_end():
208
+ trade.close_positions(position_type='all', comment=comment)
209
+ logger.info(f"End of the Day !!! SYMBOL={trade.symbol}, STRATEGY=SMA")
210
+ trade.statistics(save=True)
211
+ break
212
+
213
+
214
+ # ========= PAIR TRADING =====================
215
+ def pair_trading(
216
+ pair: List[str] | Tuple[str],
217
+ p0: Trade,
218
+ p1: Trade,
219
+ tf: str,
220
+ /,
221
+ max_t: Optional[int] = 1,
222
+ mm: Optional[bool] = True,
223
+ iter_time: Optional[int | float] = 30,
224
+ risk_manager: Optional[str] = None,
225
+ rm_ticker: Optional[str] = None,
226
+ rm_window: Optional[int] = None,
227
+ period: Literal['day', 'week', 'month'] = 'month',
228
+ **kwargs
229
+ ):
230
+ """
231
+ Implements a pair trading strategy with optional risk management
232
+ using Hidden Markov Models (HMM). This strategy trades pairs of assets
233
+ based on their historical price relationship, seeking to capitalize on converging prices.
234
+
235
+ :param pair (list[str] | tuple[str]): The trading pair represented as a list or tuple of symbols (e.g., ['AAPL', 'GOOG']).
236
+ :param p0 (Trade): Trade object for the first asset in the pair.
237
+ :param p1 (Trade): Trade object for the second asset in the pair.
238
+ :param tf (str): Time frame for the trading strategy (e.g., '1h' for 1 hour).
239
+ :param max_t (int, optional): Maximum number of trades allowed at any time for each asset in the pair, defaults to 1.
240
+
241
+ :param mm (bool, optional): Money management flag to enable/disable money management, defaults to True.
242
+ :param iter_time (int | float ,optional): Iteration time (in minutes) for the trading loop, defaults to 30.
243
+ :param risk_manager: Specifies the risk management model to use default is None , Hidden Markov Model ('hmm) Can be use.
244
+ :param rm_window: Window size for the risk model use for the prediction, defaults to None. Must be specified if `risk_manager` is not None.
245
+
246
+ :param period (str, optional): Trading period to reset statistics and close positions, can be 'day', 'week', or 'month'.
247
+ :param kwargs: Additional keyword arguments for HMM risk manager.
248
+
249
+ This function continuously evaluates the defined pair for trading opportunities
250
+ based on the strategy logic, taking into account the specified risk management
251
+ approach if applicable. It aims to profit from the mean reversion behavior typically
252
+ observed in closely related financial instruments.
253
+
254
+ Note:
255
+ This function includes an infinite loop with time delays designed to run continuously during market hours.
256
+ Proper exception handling and resource management are crucial for live trading environments.
257
+ """
258
+ regime = False
259
+ if risk_manager is not None:
260
+ assert rm_ticker is not None
261
+ assert rm_window is not None
262
+ regime = True
263
+
264
+ def p0_check(p0_positions):
265
+ if p0_positions is not None:
266
+ logger.info(f"Checking for breakeven on {pair[0]} positions...STRATEGY=KLF")
267
+ p0.break_even()
268
+
269
+ def p1_check(p1_positions):
270
+ if p1_positions is not None:
271
+ logger.info(f"Checking for breakeven on {pair[1]} positions...STRATEGY=KLF")
272
+ p1.break_even()
273
+
274
+ time_frame_mapping = tf_mapping()
275
+ if tf == 'D1':
276
+ trade_time = p0.get_minutes()
277
+ else:
278
+ trade_time = time_frame_mapping[tf]
279
+
280
+ if regime:
281
+ if risk_manager == 'hmm':
282
+ rate = Rates(rm_ticker, tf, 0)
283
+ data = rate.get_rates_from_pos()
284
+ hmm = HMMRiskManager(data=data, verbose=True, iterations=5000, **kwargs)
285
+
286
+ time_intervals = 0
287
+ long_market = False
288
+ short_market = False
289
+ num_days = 0
290
+ logger.info(
291
+ f'Running KLF Strategy on {pair[0]} and {pair[1]} in {tf} Interval ...\n')
292
+ while True:
293
+ current_date = datetime.now()
294
+ today = current_date.strftime("%A")
295
+ try:
296
+ # Data Retrieval
297
+ p0_ = Rates(pair[0], tf, 0, 10)
298
+ p1_ = Rates(pair[1], tf, 0, 10)
299
+
300
+ p0_data = p0_.get_close
301
+ p1_data = p1_.get_close
302
+ prices = np.array(
303
+ [p0_data.values[-1], p1_data.values[-1]]
304
+ )
305
+ strategy = KLFStrategy(pair)
306
+ if regime:
307
+ if risk_manager == 'hmm':
308
+ hmm_data = Rates(rm_ticker, tf, 0, rm_window)
309
+ returns = hmm_data.get_returns.values
310
+ current_regime = hmm.which_trade_allowed(returns)
311
+ logger.info(f'CURRENT REGIME ={current_regime}, STRATEGY=KLF')
312
+ else:
313
+ current_regime = None
314
+
315
+ p0_positions = p0.get_current_open_positions()
316
+ time.sleep(0.5)
317
+ p1_positions = p1.get_current_open_positions()
318
+ time.sleep(0.5)
319
+ p1_buys = p1.get_current_buys()
320
+ p0_buys = p0.get_current_buys()
321
+ time.sleep(0.5)
322
+ if p1_buys is not None:
323
+ logger.info(f"Current buy positions on {pair[1]}: {p1_buys}, STRATEGY=KLF")
324
+ if p0_buys is not None:
325
+ logger.info(f"Current buy positions on {pair[0]}: {p0_buys}, STRATEGY=KLF")
326
+ time.sleep(0.5)
327
+ p1_sells = p1.get_current_sells()
328
+ p0_sells = p0.get_current_sells()
329
+ time.sleep(0.5)
330
+ if p1_sells is not None:
331
+ logger.info(f"Current sell positions on {pair[1]}: {p1_sells}, STRATEGY=KLF")
332
+ if p0_sells is not None:
333
+ logger.info(f"Current sell positions on {pair[0]}: {p0_sells}, STRATEGY=KLF")
334
+
335
+ p1_long_market = p1_buys is not None and len(p1_buys) >= max_t
336
+ p0_long_market = p0_buys is not None and len(p0_buys) >= max_t
337
+ p1_short_market = p1_sells is not None and len(p1_sells) >= max_t
338
+ p0_short_market = p0_sells is not None and len(p0_sells) >= max_t
339
+
340
+ logger.info(f"Calculating Signals SYMBOL={pair}...STRATEGY=KLF")
341
+ signals = strategy.calculate_signals(prices)
342
+ comment = f"{p0.expert_name}@{p0.version}"
343
+
344
+ if signals is not None:
345
+ logger.info(f'SIGNALS = {signals}, STRATEGY=KLF')
346
+ if p0.trading_time() and today in TRADING_DAYS:
347
+ p1_signal = signals[pair[1]]
348
+ p0_signal = signals[pair[0]]
349
+ if p1_signal == "EXIT" and p0_signal == "EXIT":
350
+ if p1_positions is not None:
351
+ logger.info(f"Exiting Positions On [{pair[1]}], STRATEGY=KLF")
352
+ p1.close_positions(position_type='all', comment=comment)
353
+ p1_long_market = False
354
+ p1_short_market = False
355
+ if p0_positions is not None:
356
+ logger.info(f"Exiting Positions On [{pair[0]}], STRATEGY=KLF")
357
+ p0.close_positions(position_type='all', comment=comment)
358
+ p1_long_market = False
359
+ p1_short_market = False
360
+ if current_regime is not None:
361
+ if (
362
+ p1_signal == "LONG"
363
+ and p0_signal == "SHORT"
364
+ and current_regime == 'LONG'
365
+ ):
366
+ if not p1_long_market:
367
+ if time_intervals % trade_time == 0 or p1_buys is None:
368
+ logger.info(f"Going LONG on [{pair[1]}], STRATEGY=KLF")
369
+ p1.open_buy_position(
370
+ mm=mm, comment=comment)
371
+ else:
372
+ p1_check(p1_positions)
373
+ else:
374
+ logger.info(f"Sorry Risk Not allowed on [{pair[1]}], STRATEGY=KLF")
375
+ p1_check(p1_positions)
376
+
377
+ if not p0_short_market:
378
+ if time_intervals % trade_time == 0 or p0_sells is None:
379
+ logger.info(f"Going SHORT on [{pair[0]}]")
380
+ p0.open_sell_position(
381
+ mm=mm, comment=comment)
382
+ else:
383
+ p0_check(p0_positions)
384
+ else:
385
+ logger.info(
386
+ f"Sorry Risk Not allowed on [{pair[0]}], STRATEGY=KLF")
387
+ p0_check(p0_positions)
388
+ elif (
389
+ p1_signal == "SHORT"
390
+ and p0_signal == "LONG"
391
+ and current_regime == 'SHORT'
392
+ ):
393
+ if not p1_short_market:
394
+ if time_intervals % trade_time == 0 or p1_sells is None:
395
+ logger.info(f"Going SHORT on [{pair[1]}], STRATEGY=KLF")
396
+ p1.open_sell_position(
397
+ mm=mm, comment=comment)
398
+ else:
399
+ p1_check(p1_positions)
400
+ else:
401
+ logger.info(f"Sorry Risk Not allowed on [{pair[1]}], STRATEGY=KLF")
402
+ p1_check(p1_positions)
403
+
404
+ if not p0_long_market:
405
+ if time_intervals % trade_time == 0 or p0_buys is None:
406
+ logger.info(f"Going LONG on [{pair[0]}], STRATEGY=KLF")
407
+ p0.open_buy_position(
408
+ mm=mm, comment=comment)
409
+ else:
410
+ p0_check(p0_positions)
411
+ else:
412
+ logger.info(
413
+ f"Sorry Risk Not allowed on [{pair[0]}], STRATEGY=KLF")
414
+ p0_check(p0_positions)
415
+ else:
416
+ if (
417
+ p1_signal == "LONG"
418
+ and p0_signal == "SHORT"
419
+ ):
420
+ if not p1_long_market:
421
+ if time_intervals % trade_time == 0 or p1_buys is None:
422
+ logger.info(f"Going LONG on [{pair[1]}], STRATEGY=KLF")
423
+ p1.open_buy_position(
424
+ mm=mm, comment=comment)
425
+ else:
426
+ p1_check(p1_positions)
427
+ else:
428
+ logger.info(f"Sorry Risk Not allowed on [{pair[1]}], STRATEGY=KLF")
429
+ p1_check(p1_positions)
430
+
431
+ if not p0_short_market:
432
+ if time_intervals % trade_time == 0 or p0_sells is None:
433
+ logger.info(f"Going SHORT on [{pair[0]}], STRATEGY=KLF")
434
+ p0.open_sell_position(
435
+ mm=mm, comment=comment)
436
+ else:
437
+ p0_check(p0_positions)
438
+ else:
439
+ logger.info(
440
+ f"Sorry Risk Not allowed on [{pair[0]}], STRATEGY=KLF")
441
+ p0_check(p0_positions)
442
+ elif (
443
+ p1_signal == "SHORT"
444
+ and p0_signal == "LONG"
445
+ ):
446
+ if not p1_short_market:
447
+ if time_intervals % trade_time == 0 or p1_sells is None:
448
+ logger.info(f"Going SHORT on [{pair[1]}], STRATEGY=KLF")
449
+ p1.open_sell_position(
450
+ mm=mm, comment=comment)
451
+ else:
452
+ p1_check(p1_positions)
453
+ else:
454
+ logger.info(f"Sorry Risk Not allowed on [{pair[1]}], STRATEGY=KLF")
455
+ p1_check(p1_positions)
456
+
457
+ if not p0_long_market:
458
+ if time_intervals % trade_time == 0 or p0_buys is None:
459
+ logger.info(f"Going LONG on [{pair[0]}], STRATEGY=KLF")
460
+ p0.open_buy_position(
461
+ mm=mm, comment=comment)
462
+ else:
463
+ p0_check(p0_positions)
464
+ else:
465
+ logger.info(
466
+ f"Sorry Risk Not allowed on [{pair[0]}], STRATEGY=KLF")
467
+ p0_check(p0_positions)
468
+ else:
469
+ logger.info(
470
+ f"It is Not trading time !!! STRATEGY=KLF, SYMBOLS={pair}")
471
+ p0_check(p0_positions)
472
+ p1_check(p1_positions)
473
+ else:
474
+ logger.info(
475
+ f"There is no signal !!! STRATEGY=KLF, SYMBOLS={pair}")
476
+
477
+ p0_check(p0_positions)
478
+ p1_check(p1_positions)
479
+
480
+ except Exception as e:
481
+ logger.error(f"{e}, STRATEGY=KLF, SYMBOLS={pair}")
482
+
483
+ time.sleep((60 * iter_time) - 2.5)
484
+
485
+ if iter_time == 1:
486
+ time_intervals += 1
487
+ elif iter_time == trade_time:
488
+ time_intervals += trade_time
489
+ else:
490
+ time_intervals += (trade_time/iter_time)
491
+
492
+ if period.lower() == 'month':
493
+ if p0.days_end() and today != 'Friday':
494
+ logger.info(
495
+ f"End of the Day !!! STRATEGY=KLF, SYMBOLS={pair}")
496
+
497
+ sleep_time = p0.sleep_time()
498
+ time.sleep(60 * sleep_time)
499
+ num_days += 1
500
+
501
+ elif p0.days_end() and today == 'Friday':
502
+ logger.info(
503
+ f"End of the Week !!! STRATEGY=KLF, SYMBOLS={pair}")
504
+ sleep_time = p0.sleep_time(weekend=True)
505
+ time.sleep(60 * sleep_time)
506
+ num_days += 1
507
+
508
+ elif (
509
+ p0.days_end()
510
+ and today == 'Friday'
511
+ and num_days >= 20
512
+ ):
513
+ p0.close_positions(position_type='all', comment=comment)
514
+ p1.close_positions(position_type='all', comment=comment)
515
+ logger.info(
516
+ f"End of the Month !!! STRATEGY=KLF, SYMBOLS={pair}")
517
+ p0.statistics(save=True)
518
+ p1.statistics(save=True)
519
+ break
520
+
521
+ elif period.lower() == 'week':
522
+ if p0.days_end() and today != 'Friday':
523
+ sleep_time = p0.sleep_time()
524
+ time.sleep(60 * sleep_time)
525
+
526
+ elif p0.days_end() and today == 'Friday':
527
+ p0.close_positions(position_type='all', comment=comment)
528
+ p1.close_positions(position_type='all', comment=comment)
529
+ logger.info(
530
+ f"End of the Week !!! STRATEGY=KLF, SYMBOLS={pair}")
531
+ p0.statistics(save=True)
532
+ p1.statistics(save=True)
533
+ break
534
+
535
+ elif period.lower() == 'day':
536
+ if p0.days_end():
537
+ p0.close_positions(position_type='all', comment=comment)
538
+ p1.close_positions(position_type='all', comment=comment)
539
+ logger.info(
540
+ f"End of the Day !!! STRATEGY=KLF, SYMBOLS={pair}")
541
+ p0.statistics(save=True)
542
+ p1.statistics(save=True)
543
+ break
544
+
545
+
546
+ # ========= ORNSTEIN UHLENBECK TRADING ========
547
+ def ou_trading(
548
+ trade: Trade,
549
+ tf: Optional[str] = '1h',
550
+ p: Optional[int] = 20,
551
+ n: Optional[int] = 20,
552
+ ou_window: Optional[int] = 2000,
553
+ max_t: Optional[int] = 1,
554
+ mm: Optional[bool] = True,
555
+ iter_time: Optional[int | float] = 30,
556
+ risk_manager: Optional[str] = None,
557
+ rm_window: Optional[int] = None,
558
+ period: Literal['day', 'week', 'month'] = 'month',
559
+ **kwargs
560
+ ):
561
+ """
562
+ Executes the Ornstein-Uhlenbeck (OU) trading strategy,
563
+ incorporating various risk management and trading frequency adjustments.
564
+
565
+ :param trade: A `Trade` instance, containing methods and attributes for executing trades.
566
+ :param tf: Time frame for the trading strategy, default is '1h'.
567
+ :param mm: Boolean indicating if money management is enabled, default is True.
568
+ :param max_t: Maximum number of trades allowed at any given time, default is 1.
569
+ :param p: Period length for calculating returns, default is 20.
570
+ :param n: Window size for the Ornstein-Uhlenbeck strategy calculation, default is 20.
571
+ :param iter_time: Iteration time for the trading loop, can be an integer or float.
572
+ :param ou_window: Lookback period for the OU strategy, defaults to 2000.
573
+ :param risk_manager: Specifies the risk management model to use
574
+ default is None , Hidden Markov Model ('hmm) Can be use.
575
+ :param rm_window: Window size for the risk model use for the prediction, defaults to None.
576
+ Must be specified if `risk_manager` is not None.
577
+ :param period: Defines the trading period as 'month', 'week', or 'day'
578
+ affecting how and when positions are closed.
579
+ :param kwargs: Additional keyword arguments for risk management models or other customizations.
580
+
581
+ This function manages trading based on the OU strategy, adjusting for risk and time-based criteria.
582
+ It includes handling of trading sessions, buy/sell signal generation, risk management through the HMM model, and period-based
583
+ trading evaluation.
584
+ """
585
+ regime = False
586
+ if risk_manager is not None:
587
+ if risk_manager.lower() == 'hmm':
588
+ assert rm_window is not None
589
+ regime = True
590
+
591
+ rate = Rates(trade.symbol, tf, 0)
592
+ data = rate.get_rates_from_pos()
593
+ def check(buys: list, sells: list):
594
+ if buys is not None or sells is not None:
595
+ logger.info(f"Checking for Break even on {trade.symbol}... STRATEGY=OU")
596
+ trade.break_even()
597
+
598
+ time_frame_mapping = tf_mapping()
599
+ if tf == 'D1':
600
+ trade_time = trade.get_minutes()
601
+ else:
602
+ trade_time = time_frame_mapping[tf]
603
+
604
+ if regime:
605
+ if risk_manager == 'hmm':
606
+ hmm = HMMRiskManager(data=data, verbose=True, **kwargs)
607
+ strategy = OrnsteinUhlenbeck(data['Close'].values[-ou_window:], timeframe=tf)
608
+
609
+ time_intervals = 0
610
+ long_market = False
611
+ short_market = False
612
+ num_days = 0
613
+ logger.info(f'Running OU Strategy on {trade.symbol} in {tf} Interval ...\n')
614
+ while True:
615
+ current_date = datetime.now()
616
+ today = current_date.strftime("%A")
617
+ try:
618
+ buys = trade.get_current_buys()
619
+ if buys is not None:
620
+ logger.info(f"Current buy positions on {trade.symbol}: {buys}, STRATEGY=OU")
621
+ sells = trade.get_current_sells()
622
+ if sells is not None:
623
+ logger.info(f"Current sell positions on {trade.symbol}: {sells}, STRATEGY=OU")
624
+ long_market = buys is not None and len(buys) >= max_t
625
+ short_market = sells is not None and len(sells) >= max_t
626
+
627
+ time.sleep(0.5)
628
+ if regime:
629
+ if risk_manager == 'hmm':
630
+ hmm_returns = Rates(trade.symbol, tf, 0, rm_window)
631
+ hmm_returns_val = hmm_returns.get_returns.values
632
+ current_regime = hmm.which_trade_allowed(hmm_returns_val)
633
+ logger.info(
634
+ f'CURRENT REGIME = {current_regime}, SYMBOL={trade.symbol}, STRATEGY=OU')
635
+ else:
636
+ current_regime = None
637
+ logger.info(f"Calculating signal... SYMBOL={trade.symbol}, STRATEGY=OU")
638
+ ou_returns = Rates(trade.symbol, tf, 0, p)
639
+ returns_val = ou_returns.get_returns.values
640
+ signal = strategy.calculate_signals(returns_val, p=p, n=n)
641
+ comment = f"{trade.expert_name}@{trade.version}"
642
+ if trade.trading_time() and today in TRADING_DAYS:
643
+ if signal is not None:
644
+ logger.info(f"SIGNAL = {signal}, SYMBOL={trade.symbol}, STRATEGY=OU")
645
+ if signal == "LONG" and short_market:
646
+ trade.close_positions(position_type='sell')
647
+ short_market = False
648
+ elif signal == "SHORT" and long_market:
649
+ trade.close_positions(position_type='buy')
650
+ long_market = False
651
+ if current_regime is not None:
652
+ if current_regime == 'LONG':
653
+ if signal == "LONG" and not long_market:
654
+ if time_intervals % trade_time == 0 or buys is None:
655
+ logger.info(f"Sending buy Order .... SYMBOL={trade.symbol}, STRATEGY=OU")
656
+ trade.open_buy_position(
657
+ mm=mm, comment=comment)
658
+ else:
659
+ check(buys, sells)
660
+
661
+ elif signal == "LONG" and long_market:
662
+ logger.info(f"Sorry Risk not allowed !!! SYMBOL={trade.symbol}, STRATEGY=OU")
663
+ check(buys, sells)
664
+
665
+ elif current_regime == 'SHORT':
666
+ if signal == "SHORT" and not short_market:
667
+ if time_intervals % trade_time == 0 or sells is None:
668
+ logger.info(f"Sending Sell Order .... SYMBOL={trade.symbol}, STRATEGY=OU")
669
+ trade.open_sell_position(
670
+ mm=mm, comment=comment)
671
+ else:
672
+ check(buys, sells)
673
+ elif signal == "SHORT" and short_market:
674
+ logger.info(f"Sorry Risk not Allowed !!! SYMBOL={trade.symbol}, STRATEGY=OU")
675
+ check(buys, sells)
676
+ else:
677
+ if signal == "LONG" and not long_market:
678
+ if time_intervals % trade_time == 0 or buys is None:
679
+ logger.info(f"Sending buy Order .... SYMBOL={trade.symbol}, STRATEGY=OU")
680
+ trade.open_buy_position(mm=mm, comment=comment)
681
+ else:
682
+ check(buys, sells)
683
+
684
+ elif signal == "LONG" and long_market:
685
+ logger.info(f"Sorry Risk not allowed !!! SYMBOL={trade.symbol}, STRATEGY=OU")
686
+ check(buys, sells)
687
+
688
+ if signal == "SHORT" and not short_market:
689
+ if time_intervals % trade_time == 0 or sells is None:
690
+ logger.info(f"Sending Sell Order .... SYMBOL={trade.symbol}, STRATEGY=OU")
691
+ trade.open_sell_position(
692
+ mm=mm, comment=comment)
693
+ else:
694
+ check(buys, sells)
695
+ elif signal == "SHORT" and short_market:
696
+ logger.info(f"Sorry Risk not Allowed !!! SYMBOL={trade.symbol}, STRATEGY=OU")
697
+ check(buys, sells)
698
+ else:
699
+ logger.info(f"There is no signal !!! SYMBOL={trade.symbol}, STRATEGY=OU")
700
+ check(buys, sells)
701
+ else:
702
+ logger.info(f"Sorry It is Not trading Time !!! SYMBOL={trade.symbol}, STRATEGY=OU")
703
+ check(buys, sells)
704
+ except Exception as e:
705
+ print(f"{e}, SYMBOL={trade.symbol}, STRATEGY=OU")
706
+ time.sleep((60 * iter_time) - 1.5)
707
+ if iter_time == 1:
708
+ time_intervals += 1
709
+ elif iter_time == trade_time:
710
+ time_intervals += trade_time
711
+ else:
712
+ time_intervals += (trade_time/iter_time)
713
+
714
+ if period.lower() == 'month':
715
+ if trade.days_end() and today != 'Friday':
716
+ logger.info(f"End of the Day !!! SYMBOL={trade.symbol}, STRATEGY=OU")
717
+ sleep_time = trade.sleep_time()
718
+ time.sleep(60 * sleep_time)
719
+ num_days += 1
720
+
721
+ elif trade.days_end() and today == 'Friday':
722
+ logger.info(f"End of the Week !!! SYMBOL={trade.symbol}, STRATEGY=OU")
723
+ sleep_time = trade.sleep_time(weekend=True)
724
+ time.sleep(60 * sleep_time)
725
+ num_days += 1
726
+
727
+ elif (
728
+ trade.days_end()
729
+ and today == 'Friday'
730
+ and num_days >= 20
731
+ ):
732
+ trade.close_positions(position_type='all', comment=comment)
733
+ logger.info(f"End of the Month !!! SYMBOL={trade.symbol}, STRATEGY=OU")
734
+ trade.statistics(save=True)
735
+ break
736
+
737
+ elif period.lower() == 'week':
738
+ if trade.days_end() and today != 'Friday':
739
+ sleep_time = trade.sleep_time()
740
+ time.sleep(60 * sleep_time)
741
+
742
+ elif trade.days_end() and today == 'Friday':
743
+ trade.close_positions(position_type='all', comment=comment)
744
+ logger.info(f"End of the Week !!! SYMBOL={trade.symbol}, STRATEGY=OU")
745
+ trade.statistics(save=True)
746
+ break
747
+
748
+ elif period.lower() == 'day':
749
+ if trade.days_end():
750
+ trade.close_positions(position_type='all', comment=comment)
751
+ logger.info(f"End of the Day !!! SYMBOL={trade.symbol}, STRATEGY=OU")
752
+ trade.statistics(save=True)
753
+ break
754
+
755
+
756
+ # ========= ARIMA + GARCH TRADING =======================
757
+ def arch_trading(
758
+ trade: Trade,
759
+ tf: str = 'D1',
760
+ k: int = 500,
761
+ max_t: Optional[int] = 1,
762
+ mm: Optional[bool] = True,
763
+ iter_time: Optional[int | float] = 30,
764
+ risk_manager: Optional[str] = None,
765
+ rm_window: Optional[int] = None,
766
+ period: Literal['day', 'week', 'month'] = 'month',
767
+ **kwargs
768
+ ):
769
+ """
770
+ Executes trading based on the ARCH (Autoregressive Conditional Heteroskedasticity) model, with
771
+ the capability to incorporate a risk management strategy, specifically a Hidden Markov Model (HMM),
772
+ to adjust trading decisions based on the market regime.
773
+
774
+ :param trade: A `Trade` instance, necessary for executing trades and managing positions.
775
+ :param tf: Time frame for the trading data, default is 'D1' (daily).
776
+ :param k: Number of past points to consider for the ARCH model analysis, default is 500.
777
+ :param mm: Boolean flag indicating if money management strategies should be applied, default is True.
778
+ :param max_t: Maximum number of trades allowed at any given time, default is 1.
779
+ :param iter_time: Time in minutes between each iteration of the trading loop. Can be an integer or float.
780
+ :param risk_manager: Specifies the risk management model to use. Default is None.
781
+ :param rm_window: Window size for the risk model use for the prediction, defaults to None.
782
+ Must be specified if `risk_manager` is not None.
783
+ :param period: Trading period to consider for closing positions, options are 'month', 'week', or 'day'.
784
+ This affects the frequency at which statistics are calculated and positions are closed.
785
+ :param kwargs: Additional keyword arguments for the risk management models or other strategy-specific settings.
786
+
787
+ This function is designed to perform trading based on ARCH model predictions, managing risk using an HMM where
788
+ applicable, and handling trade executions and position management based on the specified parameters. It includes
789
+ considerations for trading times, money management, and periodic evaluation of trading performance.
790
+ """
791
+ regime = False
792
+ if risk_manager is not None:
793
+ if risk_manager.lower() == 'hmm':
794
+ assert rm_window is not None
795
+ regime = True
796
+
797
+ def check(buys: list, sells: list):
798
+ if buys is not None or sells is not None:
799
+ logger.info(f"Checking for Break even on {trade.symbol}...")
800
+ trade.break_even()
801
+
802
+ time_frame_mapping = tf_mapping()
803
+ if tf == 'D1':
804
+ trade_time = trade.get_minutes()
805
+ else:
806
+ trade_time = time_frame_mapping[tf]
807
+
808
+ rate = Rates(trade.symbol, tf, 0)
809
+ data = rate.get_rates_from_pos()
810
+ strategy = ArimaGarchStrategy(trade.symbol, data, k=k)
811
+ if regime:
812
+ if risk_manager == 'hmm':
813
+ hmm = HMMRiskManager(data=data, verbose=True, iterations=5000, **kwargs)
814
+
815
+ time_intervals = 0
816
+ long_market = False
817
+ short_market = False
818
+ num_days = 0
819
+ logger.info(
820
+ f'Running ARIMA + GARCH Strategy on {trade.symbol} in {tf} Interval ...\n')
821
+ while True:
822
+ current_date = datetime.now()
823
+ today = current_date.strftime("%A")
824
+ try:
825
+ buys = trade.get_current_buys()
826
+ if buys is not None:
827
+ logger.info(f"Current buy positions on {trade.symbol}: {buys}, STRATEGY=ARCH")
828
+ sells = trade.get_current_sells()
829
+ if sells is not None:
830
+ logger.info(f"Current sell positions on {trade.symbol}: {sells}, STRATEGY=ARCH")
831
+ long_market = buys is not None and len(buys) >= max_t
832
+ short_market = sells is not None and len(sells) >= max_t
833
+
834
+ time.sleep(0.5)
835
+ if regime:
836
+ if risk_manager == 'hmm':
837
+ hmm_returns = Rates(trade.symbol, tf, 0, rm_window)
838
+ hmm_returns_val = hmm_returns.get_returns.values
839
+ current_regime = hmm.which_trade_allowed(hmm_returns_val)
840
+ logger.info(f'CURRENT REGIME = {current_regime}, SYMBOL={trade.symbol}, STRATEGY=ARCH')
841
+ else:
842
+ current_regime = None
843
+ logger.info(f"Calculating Signal ... SYMBOL={trade.symbol}, STRATEGY=ARCH")
844
+ arch_data = Rates(trade.symbol, tf, 0, k)
845
+ rates = arch_data.get_rates_from_pos()
846
+ arch_returns = strategy.load_and_prepare_data(rates)
847
+ window_data = arch_returns['diff_log_return'].iloc[-k:]
848
+ signal = strategy.calculate_signals(window_data)
849
+
850
+ comment = f"{trade.expert_name}@{trade.version}"
851
+ if trade.trading_time() and today in TRADING_DAYS:
852
+ if signal is not None:
853
+ logger.info(f"SIGNAL = {signal}, SYMBOL={trade.symbol}, STRATEGY=ARCH")
854
+ if signal == "LONG" and short_market:
855
+ trade.close_positions(position_type='sell')
856
+ short_market = False
857
+ elif signal == "SHORT" and long_market:
858
+ trade.close_positions(position_type='buy')
859
+ long_market = False
860
+ if current_regime is not None:
861
+ if current_regime == 'LONG':
862
+ if signal == "LONG" and not long_market:
863
+ if time_intervals % trade_time == 0 or buys is None:
864
+ logger.info(f"Sending buy Order .... SYMBOL={trade.symbol}, STRATEGY=ARCH")
865
+ trade.open_buy_position(
866
+ mm=mm, comment=comment)
867
+ else:
868
+ check(buys, sells)
869
+
870
+ elif signal == "LONG" and long_market:
871
+ logger.info(f"Sorry Risk not allowed !!! SYMBOL={trade.symbol}, STRATEGY=ARCH")
872
+ check(buys, sells)
873
+
874
+ elif current_regime == 'SHORT':
875
+ if signal == "SHORT" and not short_market:
876
+ if time_intervals % trade_time == 0 or sells is None:
877
+ logger.info(f"Sending Sell Order .... SYMBOL={trade.symbol}, STRATEGY=ARCH")
878
+ trade.open_sell_position(
879
+ mm=mm, comment=comment)
880
+ else:
881
+ check(buys, sells)
882
+ elif signal == "SHORT" and short_market:
883
+ logger.info(f"Sorry Risk not Allowed !!! SYMBOL={trade.symbol}, STRATEGY=ARCH")
884
+ check(buys, sells)
885
+ else:
886
+ if signal == "LONG" and not long_market:
887
+ if time_intervals % trade_time == 0 or buys is None:
888
+ logger.info(f"Sending buy Order .... SYMBOL={trade.symbol}, STRATEGY=ARCH")
889
+ trade.open_buy_position(mm=mm, comment=comment)
890
+ else:
891
+ check(buys, sells)
892
+
893
+ elif signal == "LONG" and long_market:
894
+ logger.info(f"Sorry Risk not allowed !!! SYMBOL={trade.symbol}, STRATEGY=ARCH")
895
+ check(buys, sells)
896
+
897
+ if signal == "SHORT" and not short_market:
898
+ if time_intervals % trade_time == 0 or sells is None:
899
+ logger.info(f"Sending Sell Order .... SYMBOL={trade.symbol}, STRATEGY=ARCH")
900
+ trade.open_sell_position(
901
+ mm=mm, comment=comment)
902
+ else:
903
+ check(buys, sells)
904
+
905
+ elif signal == "SHORT" and short_market:
906
+ logger.info(f"Sorry Risk not Allowed !!! SYMBOL={trade.symbol}, STRATEGY=ARCH")
907
+ check(buys, sells)
908
+ else:
909
+ logger.info("There is no signal !!")
910
+ check(buys, sells)
911
+ else:
912
+ logger.info(f"Sorry It is Not trading Time !!! SYMBOL={trade.symbol}, STRATEGY=ARCH")
913
+ check(buys, sells)
914
+
915
+ except Exception as e:
916
+ print(f"{e}, SYMBOL={trade.symbol}, STRATEGY=ARCH")
917
+
918
+ time.sleep((60 * iter_time) - 1.5)
919
+ if iter_time == 1:
920
+ time_intervals += 1
921
+ elif iter_time == trade_time:
922
+ time_intervals += trade_time
923
+ else:
924
+ time_intervals += (trade_time/iter_time)
925
+
926
+ if period.lower() == 'month':
927
+ if trade.days_end() and today != 'Friday':
928
+ logger.info(f"End of the Day !!! SYMBOL={trade.symbol}, STRATEGY=ARCH")
929
+ sleep_time = trade.sleep_time()
930
+ time.sleep(60 * sleep_time)
931
+ num_days += 1
932
+
933
+ elif trade.days_end() and today == 'Friday':
934
+ logger.info(f"End of the Week !!! SYMBOL={trade.symbol}, STRATEGY=ARCH")
935
+ sleep_time = trade.sleep_time(weekend=True)
936
+ time.sleep(60 * sleep_time)
937
+ num_days += 1
938
+
939
+ elif (
940
+ trade.days_end()
941
+ and today == 'Friday'
942
+ and num_days >= 20
943
+ ):
944
+ trade.close_positions(position_type='all', comment=comment)
945
+ logger.info(f"End of the Month !!! SYMBOL={trade.symbol}, STRATEGY=ARCH")
946
+ trade.statistics(save=True)
947
+ break
948
+
949
+ elif period.lower() == 'week':
950
+ if trade.days_end() and today != 'Friday':
951
+ sleep_time = trade.sleep_time()
952
+ time.sleep(60 * sleep_time)
953
+
954
+ elif trade.days_end() and today == 'Friday':
955
+ trade.close_positions(position_type='all', comment=comment)
956
+ logger.info(f"End of the Week !!! SYMBOL={trade.symbol}, STRATEGY=ARCH")
957
+ trade.statistics(save=True)
958
+ break
959
+
960
+ elif period.lower() == 'day':
961
+ if trade.days_end():
962
+ trade.close_positions(position_type='all', comment=comment)
963
+ logger.info(f"End of the Day !!! SYMBOL={trade.symbol}, STRATEGY=ARCH")
964
+ trade.statistics(save=True)
965
+ break