|
1 | 1 | from investing_algorithm_framework import Algorithm, TradingStrategy, \ |
2 | | - TimeUnit, OrderSide |
| 2 | + TimeUnit, OrderSide, DATETIME_FORMAT |
3 | 3 | import tulipy as ti |
| 4 | +import polars as pl |
| 5 | + |
4 | 6 |
|
5 | 7 | def is_below_trend(fast_series, slow_series): |
6 | 8 | return fast_series[-1] < slow_series[-1] |
@@ -39,10 +41,11 @@ class Strategy(TradingStrategy): |
39 | 41 | ] |
40 | 42 | symbols = ["BTC/EUR", "DOT/EUR"] |
41 | 43 |
|
42 | | - def __init__(self, fast, slow, trend): |
| 44 | + def __init__(self, fast, slow, trend, stop_loss_percentage=4): |
43 | 45 | self.fast = fast |
44 | 46 | self.slow = slow |
45 | 47 | self.trend = trend |
| 48 | + self.stop_loss_percentage = stop_loss_percentage |
46 | 49 | super().__init__() |
47 | 50 |
|
48 | 51 | def apply_strategy(self, algorithm: Algorithm, market_data): |
@@ -81,17 +84,35 @@ def apply_strategy(self, algorithm: Algorithm, market_data): |
81 | 84 | for trade in open_trades: |
82 | 85 | algorithm.close_trade(trade) |
83 | 86 |
|
| 87 | + # Checking manual stop losses |
| 88 | + open_trades = algorithm.get_open_trades(target_symbol) |
| 89 | + |
| 90 | + for open_trade in open_trades: |
| 91 | + filtered_df = df.filter( |
| 92 | + pl.col('Datetime') >= open_trade.opened_at.strftime(DATETIME_FORMAT) |
| 93 | + ) |
| 94 | + close_prices = filtered_df['Close'].to_numpy() |
| 95 | + current_price = market_data[f"{symbol}-ticker"] |
| 96 | + |
| 97 | + if open_trade.is_manual_stop_loss_trigger( |
| 98 | + prices=close_prices, |
| 99 | + current_price=current_price["bid"], |
| 100 | + stop_loss_percentage=self.stop_loss_percentage |
| 101 | + ): |
| 102 | + algorithm.close_trade(open_trade) |
| 103 | + |
84 | 104 |
|
85 | 105 | def create_algorithm( |
86 | 106 | name, |
87 | 107 | description, |
88 | 108 | fast, |
89 | 109 | slow, |
90 | | - trend |
| 110 | + trend, |
| 111 | + stop_loss_percentage |
91 | 112 | ) -> Algorithm: |
92 | 113 | algorithm = Algorithm( |
93 | 114 | name=name, |
94 | 115 | description=description |
95 | 116 | ) |
96 | | - algorithm.add_strategy(Strategy(fast, slow, trend)) |
| 117 | + algorithm.add_strategy(Strategy(fast, slow, trend, stop_loss_percentage)) |
97 | 118 | return algorithm |
0 commit comments