bbstrader 0.1.5__py3-none-any.whl → 0.1.7__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/__ini__.py +0 -1
- bbstrader/btengine/__init__.py +12 -9
- bbstrader/btengine/backtest.py +100 -702
- bbstrader/btengine/data.py +25 -12
- bbstrader/btengine/event.py +18 -11
- bbstrader/btengine/execution.py +67 -7
- bbstrader/btengine/performance.py +34 -1
- bbstrader/btengine/portfolio.py +24 -14
- bbstrader/btengine/strategy.py +4 -3
- bbstrader/metatrader/account.py +18 -6
- bbstrader/metatrader/rates.py +35 -12
- bbstrader/metatrader/trade.py +54 -38
- bbstrader/metatrader/utils.py +3 -2
- bbstrader/models/risk.py +39 -2
- bbstrader/trading/__init__.py +8 -1
- bbstrader/trading/execution.py +344 -923
- bbstrader/trading/strategies.py +838 -0
- bbstrader/tseries.py +603 -19
- {bbstrader-0.1.5.dist-info → bbstrader-0.1.7.dist-info}/METADATA +15 -7
- bbstrader-0.1.7.dist-info/RECORD +26 -0
- {bbstrader-0.1.5.dist-info → bbstrader-0.1.7.dist-info}/WHEEL +1 -1
- bbstrader/strategies.py +0 -681
- bbstrader/trading/run.py +0 -131
- bbstrader/trading/utils.py +0 -153
- bbstrader-0.1.5.dist-info/RECORD +0 -28
- {bbstrader-0.1.5.dist-info → bbstrader-0.1.7.dist-info}/LICENSE +0 -0
- {bbstrader-0.1.5.dist-info → bbstrader-0.1.7.dist-info}/top_level.txt +0 -0
bbstrader/trading/execution.py
CHANGED
|
@@ -1,965 +1,386 @@
|
|
|
1
|
+
from math import log
|
|
1
2
|
import time
|
|
2
|
-
import pandas as pd
|
|
3
|
-
import numpy as np
|
|
4
3
|
from datetime import datetime
|
|
5
|
-
from bbstrader.metatrader.rates import Rates
|
|
6
4
|
from bbstrader.metatrader.trade import Trade
|
|
7
|
-
from bbstrader.trading.
|
|
8
|
-
from
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
from bbstrader.
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
5
|
+
from bbstrader.trading.strategies import Strategy
|
|
6
|
+
from typing import Optional, Literal, List, Tuple, Dict
|
|
7
|
+
import MetaTrader5 as mt5
|
|
8
|
+
from bbstrader.metatrader.account import INIT_MSG
|
|
9
|
+
from bbstrader.metatrader.utils import raise_mt5_error
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
_TF_MAPPING = {
|
|
13
|
+
'1m': 1,
|
|
14
|
+
'3m': 3,
|
|
15
|
+
'5m': 5,
|
|
16
|
+
'10m': 10,
|
|
17
|
+
'15m': 15,
|
|
18
|
+
'30m': 30,
|
|
19
|
+
'1h': 60,
|
|
20
|
+
'2h': 120,
|
|
21
|
+
'4h': 240,
|
|
22
|
+
'D1': 1440
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
TRADING_DAYS = [
|
|
26
|
+
'monday',
|
|
27
|
+
'tuesday',
|
|
28
|
+
'wednesday',
|
|
29
|
+
'thursday',
|
|
30
|
+
'friday'
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
def _check_mt5_connection():
|
|
34
|
+
if not mt5.initialize():
|
|
35
|
+
raise_mt5_error(INIT_MSG)
|
|
36
|
+
|
|
37
|
+
def _mt5_execution(
|
|
38
|
+
symbol_list, trades_instances, strategy_cls, /,
|
|
39
|
+
mm, time_frame, iter_time, period, trading_days,
|
|
40
|
+
comment, **kwargs
|
|
30
41
|
):
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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()
|
|
42
|
+
symbols = symbol_list.copy()
|
|
43
|
+
STRATEGY = kwargs.get('strategy_name')
|
|
44
|
+
_max_trades = kwargs.get('max_trades')
|
|
45
|
+
logger = kwargs.get('logger')
|
|
46
|
+
max_trades = {symbol: _max_trades[symbol] for symbol in symbols}
|
|
47
|
+
if comment is None:
|
|
48
|
+
trade = trades_instances[symbols[0]]
|
|
49
|
+
comment = f"{trade.expert_name}@{trade.version}"
|
|
50
|
+
|
|
51
|
+
def check(buys: List, sells: List, symbol: str):
|
|
52
|
+
if not mm:
|
|
53
|
+
return
|
|
54
|
+
if buys is not None:
|
|
55
|
+
logger.info(
|
|
56
|
+
f"Checking for Break even, SYMBOL={symbol}...STRATEGY={STRATEGY}")
|
|
57
|
+
trades_instances[symbol].break_even(mm=mm)
|
|
58
|
+
if sells is not None:
|
|
59
|
+
logger.info(
|
|
60
|
+
f"Checking for Break even, SYMBOL={symbol}...STRATEGY={STRATEGY}")
|
|
61
|
+
trades_instances[symbol].break_even(mm=mm)
|
|
62
|
+
num_days = 0
|
|
63
|
+
time_intervals = 0
|
|
64
|
+
trade_time = _TF_MAPPING[time_frame]
|
|
83
65
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
trade_time = trade.get_minutes()
|
|
87
|
-
else:
|
|
88
|
-
trade_time = time_frame_mapping[tf]
|
|
66
|
+
long_market = {symbol: False for symbol in symbols}
|
|
67
|
+
short_market = {symbol: False for symbol in symbols}
|
|
89
68
|
|
|
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
69
|
logger.info(
|
|
100
|
-
f'Running
|
|
70
|
+
f'Running {STRATEGY} Strategy on {symbols} in {time_frame} Interval ...')
|
|
71
|
+
strategy: Strategy = strategy_cls(
|
|
72
|
+
symbol_list=symbols, mode='live', **kwargs)
|
|
73
|
+
|
|
101
74
|
while True:
|
|
102
|
-
current_date = datetime.now()
|
|
103
|
-
today = current_date.strftime("%A")
|
|
104
75
|
try:
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
-
|
|
76
|
+
_check_mt5_connection()
|
|
77
|
+
current_date = datetime.now()
|
|
78
|
+
today = current_date.strftime("%A").lower()
|
|
116
79
|
time.sleep(0.5)
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
if
|
|
127
|
-
logger.info(
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
80
|
+
buys = {
|
|
81
|
+
symbol: trades_instances[symbol].get_current_buys()
|
|
82
|
+
for symbol in symbols
|
|
83
|
+
}
|
|
84
|
+
sells = {
|
|
85
|
+
symbol: trades_instances[symbol].get_current_sells()
|
|
86
|
+
for symbol in symbols
|
|
87
|
+
}
|
|
88
|
+
for symbol in symbols:
|
|
89
|
+
if buys[symbol] is not None:
|
|
90
|
+
logger.info(
|
|
91
|
+
f"Current buy positions SYMBOL={symbol}: {buys[symbol]}, STRATEGY={STRATEGY}")
|
|
92
|
+
if sells[symbol] is not None:
|
|
93
|
+
logger.info(
|
|
94
|
+
f"Current sell positions SYMBOL={symbol}: {sells[symbol]}, STRATEGY={STRATEGY}")
|
|
95
|
+
long_market = {symbol: buys[symbol] is not None and len(
|
|
96
|
+
buys[symbol]) >= max_trades[symbol] for symbol in symbols}
|
|
97
|
+
short_market = {symbol: sells[symbol] is not None and len(
|
|
98
|
+
sells[symbol]) >= max_trades[symbol] for symbol in symbols}
|
|
99
|
+
except Exception as e:
|
|
100
|
+
logger.error(f"{e}, STRATEGY={STRATEGY}")
|
|
101
|
+
time.sleep(0.5)
|
|
102
|
+
for symbol in symbols:
|
|
103
|
+
try:
|
|
104
|
+
trade = trades_instances[symbol]
|
|
105
|
+
logger.info(
|
|
106
|
+
f"Calculating signal... SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
107
|
+
signal = strategy.calculate_signals()[symbol]
|
|
108
|
+
if trade.trading_time() and today in trading_days:
|
|
109
|
+
if signal is not None:
|
|
110
|
+
logger.info(
|
|
111
|
+
f"SIGNAL = {signal}, SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
112
|
+
if signal in ("EXIT", "EXIT_LONG") and long_market[symbol]:
|
|
113
|
+
trade.close_positions(position_type='buy')
|
|
114
|
+
elif signal in ("EXIT", "EXIT_SHORT") and short_market[symbol]:
|
|
115
|
+
trade.close_positions(position_type='sell')
|
|
116
|
+
elif signal == "LONG" and not long_market[symbol]:
|
|
117
|
+
if time_intervals % trade_time == 0 or buys[symbol] is None:
|
|
118
|
+
logger.info(
|
|
119
|
+
f"Sending buy Order ... SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
139
120
|
trade.open_buy_position(mm=mm, comment=comment)
|
|
140
121
|
else:
|
|
141
|
-
check(buys, sells)
|
|
142
|
-
elif signal == "LONG" and long_market:
|
|
143
|
-
logger.info(
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
if time_intervals % trade_time == 0 or sells is None:
|
|
149
|
-
logger.info(
|
|
122
|
+
check(buys[symbol], sells[symbol], symbol)
|
|
123
|
+
elif signal == "LONG" and long_market[symbol]:
|
|
124
|
+
logger.info(
|
|
125
|
+
f"Sorry Risk not allowed !!! SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
126
|
+
check(buys[symbol], sells[symbol], symbol)
|
|
127
|
+
|
|
128
|
+
elif signal == "SHORT" and not short_market[symbol]:
|
|
129
|
+
if time_intervals % trade_time == 0 or sells[symbol] is None:
|
|
130
|
+
logger.info(
|
|
131
|
+
f"Sending sell Order ... SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
150
132
|
trade.open_sell_position(
|
|
151
133
|
mm=mm, comment=comment)
|
|
152
134
|
else:
|
|
153
|
-
check(buys, sells)
|
|
154
|
-
elif signal == "SHORT" and short_market:
|
|
155
|
-
logger.info(
|
|
156
|
-
|
|
157
|
-
|
|
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)
|
|
135
|
+
check(buys[symbol], sells[symbol], symbol)
|
|
136
|
+
elif signal == "SHORT" and short_market[symbol]:
|
|
137
|
+
logger.info(
|
|
138
|
+
f"Sorry Risk not allowed !!! SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
139
|
+
check(buys[symbol], sells[symbol], symbol)
|
|
415
140
|
else:
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
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)
|
|
141
|
+
logger.info(
|
|
142
|
+
f"There is no signal !! SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
143
|
+
check(buys[symbol], sells[symbol], symbol)
|
|
468
144
|
else:
|
|
469
145
|
logger.info(
|
|
470
|
-
f"It is Not trading
|
|
471
|
-
|
|
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}")
|
|
146
|
+
f"Sorry It is Not trading Time !!! SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
147
|
+
check(buys[symbol], sells[symbol], symbol)
|
|
482
148
|
|
|
483
|
-
|
|
149
|
+
except Exception as e:
|
|
150
|
+
logger.error(f"{e}, SYMBOL={symbol}, STRATEGY={STRATEGY}")
|
|
484
151
|
|
|
152
|
+
time.sleep((60 * iter_time) - 1.0)
|
|
485
153
|
if iter_time == 1:
|
|
486
154
|
time_intervals += 1
|
|
487
|
-
elif iter_time ==
|
|
488
|
-
time_intervals +=
|
|
155
|
+
elif trade_time % iter_time == 0:
|
|
156
|
+
time_intervals += iter_time
|
|
489
157
|
else:
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
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)
|
|
158
|
+
raise ValueError(
|
|
159
|
+
f"iter_time must be a multiple of the {time_frame} !!!"
|
|
160
|
+
f"(e.g; if time_frame is 15m, iter_time must be 1.5, 3, 3, 15 etc)"
|
|
161
|
+
)
|
|
162
|
+
print()
|
|
163
|
+
if period.lower() == 'day':
|
|
164
|
+
for symbol in symbols:
|
|
165
|
+
trade = trades_instances[symbol]
|
|
166
|
+
if trade.days_end():
|
|
167
|
+
trade.close_positions(position_type='all', comment=comment)
|
|
168
|
+
logger.info(
|
|
169
|
+
f"End of the Day !!! SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
170
|
+
trade.statistics(save=True)
|
|
171
|
+
if trades_instances[symbols[-1]].days_end():
|
|
519
172
|
break
|
|
520
173
|
|
|
521
174
|
elif period.lower() == 'week':
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
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
|
|
175
|
+
for symbol in symbols:
|
|
176
|
+
trade = trades_instances[symbol]
|
|
177
|
+
if trade.days_end() and today != 'friday':
|
|
178
|
+
logger.info(
|
|
179
|
+
f"End of the Day !!! SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
534
180
|
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
181
|
+
elif trade.days_end() and today == 'friday':
|
|
182
|
+
trade.close_positions(position_type='all', comment=comment)
|
|
183
|
+
logger.info(
|
|
184
|
+
f"End of the Week !!! SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
185
|
+
trade.statistics(save=True)
|
|
186
|
+
if trades_instances[symbols[-1]].days_end() and today != 'friday':
|
|
187
|
+
sleep_time = trades_instances[symbols[-1]].sleep_time()
|
|
188
|
+
logger.info(f"Sleeping for {sleep_time} minutes ...")
|
|
189
|
+
time.sleep(60 * sleep_time)
|
|
190
|
+
logger.info("\nSTARTING NEW TRADING SESSION ...")
|
|
191
|
+
elif trades_instances[symbols[-1]].days_end() and today == 'friday':
|
|
543
192
|
break
|
|
544
193
|
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
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)
|
|
194
|
+
elif period.lower() == 'month':
|
|
195
|
+
for symbol in symbols:
|
|
196
|
+
trade = trades_instances[symbol]
|
|
197
|
+
if trade.days_end() and today != 'friday':
|
|
633
198
|
logger.info(
|
|
634
|
-
f
|
|
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)
|
|
199
|
+
f"End of the Day !!! SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
660
200
|
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
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()
|
|
201
|
+
elif trade.days_end() and today == 'friday':
|
|
202
|
+
logger.info(
|
|
203
|
+
f"End of the Week !!! SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
204
|
+
elif (
|
|
205
|
+
trade.days_end()
|
|
206
|
+
and today == 'friday'
|
|
207
|
+
and num_days/len(symbols) >= 20
|
|
208
|
+
):
|
|
209
|
+
trade.close_positions(position_type='all', comment=comment)
|
|
210
|
+
logger.info(
|
|
211
|
+
f"End of the Month !!! SYMBOL={trade.symbol}, STRATEGY={STRATEGY}")
|
|
212
|
+
trade.statistics(save=True)
|
|
213
|
+
if trades_instances[symbols[-1]].days_end() and today != 'friday':
|
|
214
|
+
sleep_time = trades_instances[symbols[-1]].sleep_time()
|
|
215
|
+
logger.info(f"Sleeping for {sleep_time} minutes ...")
|
|
718
216
|
time.sleep(60 * sleep_time)
|
|
217
|
+
logger.info("\nSTARTING NEW TRADING SESSION ...")
|
|
719
218
|
num_days += 1
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
sleep_time
|
|
219
|
+
elif trades_instances[symbols[-1]].days_end() and today == 'friday':
|
|
220
|
+
sleep_time = trades_instances[symbols[-1]
|
|
221
|
+
].sleep_time(weekend=True)
|
|
222
|
+
logger.info(f"Sleeping for {sleep_time} minutes ...")
|
|
724
223
|
time.sleep(60 * sleep_time)
|
|
224
|
+
logger.info("\nSTARTING NEW TRADING SESSION ...")
|
|
725
225
|
num_days += 1
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
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)
|
|
226
|
+
elif (trades_instances[symbols[-1]].days_end()
|
|
227
|
+
and today == 'friday'
|
|
228
|
+
and num_days/len(symbols) >= 20
|
|
229
|
+
):
|
|
735
230
|
break
|
|
736
231
|
|
|
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
232
|
|
|
748
|
-
|
|
749
|
-
|
|
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
|
|
233
|
+
def _tws_execution(*args, **kwargs):
|
|
234
|
+
raise NotImplementedError("TWS Execution is not yet implemented !!!")
|
|
754
235
|
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
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
|
-
):
|
|
236
|
+
_TERMINALS = {
|
|
237
|
+
'MT5': _mt5_execution,
|
|
238
|
+
'TWS': _tws_execution
|
|
239
|
+
}
|
|
240
|
+
class ExecutionEngine():
|
|
769
241
|
"""
|
|
770
|
-
|
|
771
|
-
the
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
242
|
+
The `ExecutionEngine` class serves as the central hub for executing your trading strategies within the `bbstrader` framework.
|
|
243
|
+
It orchestrates the entire trading process, ensuring seamless interaction between your strategies, market data, and your chosen
|
|
244
|
+
trading platform (currently MetaTrader 5 (MT5) and Interactive Brokers TWS).
|
|
245
|
+
|
|
246
|
+
Key Features
|
|
247
|
+
------------
|
|
248
|
+
|
|
249
|
+
- **Strategy Execution:** The `ExecutionEngine` is responsible for running your strategy, retrieving signals, and executing trades based on those signals.
|
|
250
|
+
- **Time Management:** You can define a specific time frame for your trades and set the frequency with which the engine checks for signals and manages trades.
|
|
251
|
+
- **Trade Period Control:** Define whether your strategy runs for a day, a week, or a month, allowing for flexible trading durations.
|
|
252
|
+
- **Money Management:** The engine supports optional money management features, allowing you to control risk and optimize your trading performance.
|
|
253
|
+
- **Trading Day Configuration:** You can customize the days of the week your strategy will execute, providing granular control over your trading schedule.
|
|
254
|
+
- **Platform Integration:** The `ExecutionEngine` is currently designed to work with both MT5 and TWS platforms, ensuring compatibility and flexibility in your trading environment.
|
|
255
|
+
|
|
256
|
+
Examples
|
|
257
|
+
--------
|
|
258
|
+
|
|
259
|
+
>>> from bbstrader.metatrader import create_trade_instance
|
|
260
|
+
>>> from bbstrader.trading.execution import ExecutionEngine
|
|
261
|
+
>>> from bbstrader.trading.strategies import StockIndexCFDTrading
|
|
262
|
+
>>> from bbstrader.metatrader.utils import config_logger
|
|
263
|
+
>>>
|
|
264
|
+
>>> if __name__ == '__main__':
|
|
265
|
+
>>> logger = config_logger(index_trade.log, console_log=True)
|
|
266
|
+
>>> # Define symbols
|
|
267
|
+
>>> ndx = '[NQ100]'
|
|
268
|
+
>>> spx = '[SP500]'
|
|
269
|
+
>>> dji = '[DJI30]'
|
|
270
|
+
>>> dax = 'GERMANY40'
|
|
271
|
+
>>>
|
|
272
|
+
>>> symbol_list = [spx, dax, dji, ndx]
|
|
273
|
+
>>>
|
|
274
|
+
>>> trade_kwargs = {
|
|
275
|
+
... 'expert_id': 5134,
|
|
276
|
+
... 'version': 2.0,
|
|
277
|
+
... 'time_frame': '15m',
|
|
278
|
+
... 'var_level': 0.99,
|
|
279
|
+
... 'start_time': '8:30',
|
|
280
|
+
... 'finishing_time': '19:30',
|
|
281
|
+
... 'ending_time': '21:30',
|
|
282
|
+
... 'max_risk': 5.0,
|
|
283
|
+
... 'daily_risk': 0.10,
|
|
284
|
+
... 'pchange_sl': 1.5,
|
|
285
|
+
... 'rr': 3.0,
|
|
286
|
+
... 'logger': logger
|
|
287
|
+
... }
|
|
288
|
+
>>> strategy_kwargs = {
|
|
289
|
+
... 'max_trades': {ndx: 3, spx: 3, dji: 3, dax: 3},
|
|
290
|
+
... 'expected_returns': {ndx: 1.5, spx: 1.5, dji: 1.0, dax: 1.0},
|
|
291
|
+
... 'strategy_name': 'SISTBO',
|
|
292
|
+
... 'logger': logger,
|
|
293
|
+
... 'expert_id': 5134
|
|
294
|
+
... }
|
|
295
|
+
>>> trades_instances = create_trade_instance(
|
|
296
|
+
... symbol_list, trade_kwargs,
|
|
297
|
+
... logger=logger,
|
|
298
|
+
... )
|
|
299
|
+
>>>
|
|
300
|
+
>>> engine = ExecutionEngine(
|
|
301
|
+
... symbol_list,
|
|
302
|
+
... trades_instances,
|
|
303
|
+
... StockIndexCFDTrading,
|
|
304
|
+
... time_frame='15m',
|
|
305
|
+
... iter_time=5,
|
|
306
|
+
... mm=True,
|
|
307
|
+
... period='week',
|
|
308
|
+
... comment='bbs_SISTBO_@2.0',
|
|
309
|
+
... **strategy_kwargs
|
|
310
|
+
... )
|
|
311
|
+
>>> engine.run(terminal='MT5')
|
|
790
312
|
"""
|
|
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
313
|
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
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
|
|
314
|
+
def __init__(self,
|
|
315
|
+
symbol_list: List[str],
|
|
316
|
+
trades_instances: Dict[str, Trade],
|
|
317
|
+
strategy_cls: Strategy,
|
|
318
|
+
/,
|
|
319
|
+
mm: Optional[bool] = True,
|
|
320
|
+
time_frame: Optional[str] = '15m',
|
|
321
|
+
iter_time: Optional[int | float] = 5,
|
|
322
|
+
period: Literal['day', 'week', 'month'] = 'week',
|
|
323
|
+
trading_days: Optional[List[str]] = TRADING_DAYS,
|
|
324
|
+
comment: Optional[str] = None,
|
|
325
|
+
**kwargs
|
|
326
|
+
):
|
|
327
|
+
"""
|
|
328
|
+
Args:
|
|
329
|
+
symbol_list : List of symbols to trade
|
|
330
|
+
trades_instances : Dictionary of Trade instances
|
|
331
|
+
strategy_cls : Strategy class to use for trading
|
|
332
|
+
mm : Enable Money Management. Defaults to False.
|
|
333
|
+
time_frame : Time frame to trade. Defaults to '15m'.
|
|
334
|
+
iter_time : Interval to check for signals and `mm`. Defaults to 5.
|
|
335
|
+
period : Period to trade. Defaults to 'week'.
|
|
336
|
+
trading_days : Trading days in a week. Defaults to monday to friday.
|
|
337
|
+
comment: Comment for trades. Defaults to None.
|
|
338
|
+
**kwargs: Additional keyword arguments
|
|
339
|
+
- strategy_name (Optional[str]): Strategy name. Defaults to None.
|
|
340
|
+
- max_trades (Dict[str, int]): Maximum trades per symbol. Defaults to None.
|
|
341
|
+
- logger (Optional[logging.Logger]): Logger instance. Defaults to None.
|
|
342
|
+
|
|
343
|
+
Note:
|
|
344
|
+
1. All Strategies must inherit from `bbstrader.btengine.strategy.Strategy` class
|
|
345
|
+
and have a `calculate_signals` method that returns a dictionary of signals for each symbol in symbol_list.
|
|
346
|
+
|
|
347
|
+
2. All strategies must have the following arguments in their `__init__` method:
|
|
348
|
+
- bars (DataHandler): DataHandler instance default to None
|
|
349
|
+
- events (Queue): Queue instance default to None
|
|
350
|
+
- symbol_list (List[str]): List of symbols to trade can be none for backtesting
|
|
351
|
+
- mode (str): Mode of the strategy. Must be either 'live' or 'backtest'
|
|
352
|
+
- **kwargs: Additional keyword arguments
|
|
353
|
+
The keyword arguments are all the additional arguments passed to the `ExecutionEngine` class,
|
|
354
|
+
the `Strategy` class, the `DataHandler` class, the `Portfolio` class and the `ExecutionHandler` class.
|
|
355
|
+
- The `bars` and `events` arguments are used for backtesting only.
|
|
356
|
+
|
|
357
|
+
3. All strategies must generate signals for backtesting and live trading.
|
|
358
|
+
See the `bbstrader.trading.strategies` module for more information on how to create custom strategies.
|
|
359
|
+
"""
|
|
360
|
+
self.symbol_list = symbol_list
|
|
361
|
+
self.trades_instances = trades_instances
|
|
362
|
+
self.strategy_cls = strategy_cls
|
|
363
|
+
self.mm = mm
|
|
364
|
+
self.time_frame = time_frame
|
|
365
|
+
self.iter_time = iter_time
|
|
366
|
+
self.period = period
|
|
367
|
+
self.trading_days = trading_days
|
|
368
|
+
self.comment = comment
|
|
369
|
+
self.kwargs = kwargs
|
|
370
|
+
|
|
371
|
+
def run(self, terminal: Literal['MT5', 'TWS']):
|
|
372
|
+
if terminal not in _TERMINALS:
|
|
373
|
+
raise ValueError(
|
|
374
|
+
f"Invalid terminal: {terminal}. Must be either 'MT5' or 'TWS'")
|
|
375
|
+
_TERMINALS[terminal](
|
|
376
|
+
self.symbol_list,
|
|
377
|
+
self.trades_instances,
|
|
378
|
+
self.strategy_cls,
|
|
379
|
+
mm=self.mm,
|
|
380
|
+
time_frame=self.time_frame,
|
|
381
|
+
iter_time=self.iter_time,
|
|
382
|
+
period=self.period,
|
|
383
|
+
trading_days=self.trading_days,
|
|
384
|
+
comment=self.comment,
|
|
385
|
+
**self.kwargs
|
|
386
|
+
)
|