💬 Forum

CusTrend_coralTrend_Adx_EMA_Oct_1h

uploads/CusTrend_coralTrend_Adx_EMA_Oct_1h.py · uploaded by 🐋 Ron · first seen 2026-07-20

Basics mode: futures timeframe: 1h interface version: 3 4h
Settings stoploss: -0.347 has minimal roi trailing protections process only new candles startup candle count: 30 hyperopt hyperopt params: 17
Indicators ADX EMA RSI SAR pandas_ta talib technical
Concepts risk_management trailing trend_following
3 related strategies ( identical code, similar name)

Each tile is a different kind of check — from an instant code lint to full sandboxed backtests and forward tests on recent data. Not sure what a check actually proves? See the FAQ →

Source

Download Raw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
# flake8: noqa: F401
# isort: skip_file
# --- Do not remove these libs ---
from functools import reduce
import numpy as np
import pandas as pd
from pandas import DataFrame
from datetime import datetime
from typing import Optional, Union


from freqtrade.persistence import Trade

from freqtrade.strategy import (BooleanParameter, CategoricalParameter, stoploss_from_open, DecimalParameter,
                                IntParameter, IStrategy, informative, merge_informative_pair)

# --------------------------------
# Add your lib to import here
import talib.abstract as ta
import pandas_ta as pta
from technical import qtpylib

# custom indicators
# #############################################################################################################################################################################################


#  Coral Trend Indicator
'''
The "Coral Trend Indicator" is a trend-following indicator that uses a combination of exponential moving averages (EMAs) and the Commodity Channel Index (CCI) to identify trends and potential reversal points

This code imports the necessary libraries (pandas and numpy) and defines a function called coral_trend() that takes a DataFrame of cryptocurrency data (with a "close" column) and the EMA period, CCI period, and CCI threshold as inputs. The function first calculates the fast and slow exponential moving averages (EMAs) of the cryptocurrency and stores them in new columns called "ema_fast" and "ema_slow", respectively. It then calculates the Commodity Channel Index (CCI) of the cryptocurrency and stores it in a new column called "cci".

The function then determines the trend based on the EMAs and CCI, and stores it in a new column called "coral_trend".

The coral_trend() function determines the trend by using the np.where() function to set the value of the "coral_trend" column based on the following conditions:

    If the fast EMA is greater than the slow EMA and the CCI is less than the negative CCI threshold, then the trend is set to 1 (indicating an uptrend).
    If the fast EMA is less than the slow EMA and the CCI is greater than the positive CCI threshold, then the trend is set to -1 (indicating a downtrend).
    Otherwise, the trend is set to 0 (indicating no trend or a neutral market).

The coral_trend() function then returns the modified DataFrame with the "coral_trend" column added.
'''
def coral_trend(df, ema_period=10, cci_period=20, cci_threshold=100):
    # Calculate the exponential moving averages (EMAs)
    df['ema_fast'] = df['close'].ewm(span=ema_period, adjust=False).mean()
    df['ema_slow'] = df['close'].ewm(span=ema_period*2, adjust=False).mean()
    
    # Calculate the Commodity Channel Index (CCI)
    df['cci'] = ((df['close'] - df['close'].rolling(cci_period).mean()) / df['close'].rolling(cci_period).std()) * np.sqrt(cci_period)
    
    # Determine the trend based on the EMAs and CCI
    df['coral_trend'] = np.where((df['ema_fast'] > df['ema_slow']) & (df['cci'] < -cci_threshold), 1, 0)
    df['coral_trend'] = np.where((df['ema_fast'] < df['ema_slow']) & (df['cci'] > cci_threshold), -1, df['coral_trend'])
    
    return df


#double up and down closing based trend

def determine_trend(df):
    df['trend'] = 0
    for i in range(2, len(df)):
        close_prev = df['close'].iloc[i-1]
        close = df['close'].iloc[i]
        high_prev = df['high'].iloc[i-1]
        low_prev = df['low'].iloc[i-1]
        open_prev = df['open'].iloc[i-1]
        high = df['high'].iloc[i]
        low = df['low'].iloc[i]
        open = df['open'].iloc[i] 

        if (
            close_prev < close and
            high_prev < high and
            high_prev < close and
            low_prev < low and  # Close of previous candle is lower than present candle
            close - open > (close_prev - open_prev) and
            # close - open < 3* (close_prev - open_prev) and
            open < close and 
            open_prev < close_prev and
            # (close_prev - open_prev) < (open_prev - low_prev) and
            high_prev - close_prev < close_prev - open_prev and  # High - Close < Close - Open for previous candle
            high - close < close - open  # High - Close < Close - Open for present candle
        ):
            df.at[i, 'trend'] = 1

        elif (
            close_prev > close and
            high_prev > high and
            low_prev > low and   # Close of previous candle is higher than present candle
            low_prev > close and   # Close of previous candle is higher than present candle
            open > close and 
            open_prev > close_prev and
            # (open_prev - close_prev) < (high_prev - open_prev) and
            open - close > (open_prev - close_prev) and
            # open - close < 3* (open_prev - close_prev) and
            close_prev - low_prev < open_prev - close_prev and  # Close - Low < Open - Close for previous candle
            close - low < open - close  # Close - Low < Open - Close for present candle
        ):
            df.at[i, 'trend'] = -1

    return df



# ############################################################################################################################################################################################

class CusTrend_coralTrend_Adx_EMA_Oct_1h(IStrategy):

    
    # Strategy interface version - allow new iterations of the strategy interface.
    # Check the documentation or the Sample strategy to get the latest version.
    INTERFACE_VERSION = 3

    # Optimal timeframe for the strategy.
    timeframe = '1h'

    # Can this strategy go short?
    can_short = True



    '''

 




docker-compose run freqtrade backtesting --strategy CusTrend_coralTrend_Adx_EMA_Oct_1h -i 1h --export trades --breakdown month --timerange 20210101-20230525


    '''

    # Minimal ROI designed for the strategy.
    minimal_roi = {'0': 0.101, '373': 0.068, '1088': 0.025, '1336': 0}

    # Optimal stoploss designed for the strategy.
    # This attribute will be overridden if the config file contains "stoploss".
    stoploss = -0.347

    # Trailing stop:
    trailing_stop = True
    trailing_stop_positive = 0.011
    trailing_stop_positive_offset = 0.012
    trailing_only_offset_is_reached = True

    # Run "populate_indicators()" only for new candle.
    process_only_new_candles = True

    # These values can be overridden in the config.
    use_exit_signal = True
    exit_profit_only = False
    ignore_roi_if_entry_signal = False

    # Number of candles the strategy requires before producing valid signals
    startup_candle_count: int = 30

    #leverage here
    leverage_optimize = True
    leverage_num = IntParameter(low=1, high=5, default=5, space='buy', optimize=leverage_optimize)

    # Strategy parameters
    parameters_yes = True
    parameters_no = False

    '''
    adx_long_min = IntParameter(4, 21, default=9, space="buy", optimize = parameters_yes)
    adx_long_max = IntParameter(21, 56, default=38, space="buy", optimize = parameters_yes)
    adx_short_min = IntParameter(4, 21, default=21, space="buy", optimize = parameters_yes)
    adx_short_max = IntParameter(20, 56, default=29, space="buy", optimize = parameters_yes)

    ema_period = IntParameter(22, 200, default=175, space="buy", optimize= parameters_yes)

    volume_check = IntParameter(15, 45, default=36, space="buy", optimize= parameters_yes)
    volume_check_exit = IntParameter(15, 45, default=35, space="sell", optimize= parameters_yes)

    sell_shift = IntParameter(1, 6, default=6, space="sell", optimize= parameters_yes)
    sell_shift_short = IntParameter(1, 6, default=6, space="sell", optimize= parameters_yes) 
    
    '''
    adx_long_min = IntParameter(4, 21, default=17, space="buy", optimize = parameters_yes)
    adx_long_max = IntParameter(21, 56, default=34, space="buy", optimize = parameters_yes)
    adx_short_min = IntParameter(4, 21, default=15, space="buy", optimize = parameters_yes)
    adx_short_max = IntParameter(20, 56, default=42, space="buy", optimize = parameters_yes)

    ema_period = IntParameter(22, 200, default=50, space="buy", optimize= parameters_yes)

    volume_check = IntParameter(15, 45, default=39, space="buy", optimize= parameters_yes)
    volume_check_exit = IntParameter(15, 45, default=41, space="sell", optimize= parameters_yes)

    sell_shift = IntParameter(1, 6, default=6, space="sell", optimize= parameters_yes)
    sell_shift_short = IntParameter(1, 6, default=5, space="sell", optimize= parameters_yes)  # **added this at random-state 11165



    protect_optimize = True
    # cooldown_lookback = IntParameter(1, 40, default=4, space="protection", optimize=protect_optimize)
    max_drawdown_lookback = IntParameter(1, 50, default=2, space="protection", optimize=protect_optimize)
    max_drawdown_trade_limit = IntParameter(1, 3, default=1, space="protection", optimize=protect_optimize)
    max_drawdown_stop_duration = IntParameter(1, 50, default=4, space="protection", optimize=protect_optimize)
    max_allowed_drawdown = DecimalParameter(0.05, 0.30, default=0.10, decimals=2, space="protection",
                                            optimize=protect_optimize)
    stoploss_guard_lookback = IntParameter(1, 50, default=8, space="protection", optimize=protect_optimize)
    stoploss_guard_trade_limit = IntParameter(1, 3, default=1, space="protection", optimize=protect_optimize)
    stoploss_guard_stop_duration = IntParameter(1, 50, default=4, space="protection", optimize=protect_optimize)

    @property
    def protections(self):
        return [
            # {
            #     "method": "CooldownPeriod",
            #     "stop_duration_candles": self.cooldown_lookback.value
            # },
            {
                "method": "MaxDrawdown",
                "lookback_period_candles": self.max_drawdown_lookback.value,
                "trade_limit": self.max_drawdown_trade_limit.value,
                "stop_duration_candles": self.max_drawdown_stop_duration.value,
                "max_allowed_drawdown": self.max_allowed_drawdown.value
            },
            {
                "method": "StoplossGuard",
                "lookback_period_candles": self.stoploss_guard_lookback.value,
                "trade_limit": self.stoploss_guard_trade_limit.value,
                "stop_duration_candles": self.stoploss_guard_stop_duration.value,
                "only_per_pair": False
            }
        ]

 


    # ema_long = IntParameter(50, 250, default=100, space="buy")
    # ema_short = IntParameter(50, 250, default=100, space="buy")

    # sell_rsi = IntParameter(60, 90, default=70, space="sell")

    # Optional order type mapping.
    order_types = {
        'entry': 'limit',
        'exit': 'limit',
        'stoploss': 'market',
        'stoploss_on_exchange': False
    }

    # Optional order time in force.
    order_time_in_force = {
        'entry': 'GTC',
        'exit': 'GTC'
    }
    
    @property
    def plot_config(self):
        return {
            # Main plot indicators (Moving averages, ...)
            'main_plot': {
                'tema': {},
                'sar': {'color': 'white'},
            },
            'subplots': {
                # Subplots - each dict defines one additional plot
                "MACD": {
                    'macd': {'color': 'blue'},
                    'macdsignal': {'color': 'orange'},
                },
                "RSI": {
                    'rsi': {'color': 'red'},
                }
            }
        }

    def informative_pairs(self):
        
        # get access to all pairs available in whitelist.
        pairs = self.dp.current_whitelist()
        informative_pairs = [(pair, '4h') for pair in pairs]
        
        return informative_pairs
    

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        if not self.dp:
            # Don't do anything if DataProvider is not available.
            return dataframe
        
        inf_tf = '4h'
        # Get the informative pair
        informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf)
        # Get the 14 day rsi
        informative['ema'] = ta.EMA(informative['close'], timeperiod=50)

        # Use the helper function merge_informative_pair to safely merge the pair
        # Automatically renames the columns and merges a shorter timeframe dataframe and a longer timeframe informative pair
        # use ffill to have the 1d value available in every row throughout the day.
        # Without this, comparisons between columns of the original and the informative pair would only work once per day.
        # Full documentation of this method, see below
        dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True)

        L_determine_trend_strategy = determine_trend(df = dataframe)
        dataframe['trend'] = L_determine_trend_strategy['trend']


        # long_coral_trend = coral_trend(df=dataframe, ema_period = self.ct_ema_period.value, cci_period=self.ct_cci_period.value, cci_threshold = self.ct_cci_threshold.value)

        # dataframe['ct_ema_fast']= long_coral_trend['ema_fast']
        # dataframe['ct_ema_slow'] = long_coral_trend['ema_slow']
        # dataframe['ct_cci'] = long_coral_trend['cci']
        # dataframe['ct_coral_trend'] = long_coral_trend['coral_trend'] 


        # dataframe['psar'] = calculate_psar(df=dataframe, af_start=self.af_start_range.value, af_max=self.af_max_range.value)
        
        # Parabolic SAR
        dataframe['psar'] = ta.SAR(dataframe)

        

        # ADX
        dataframe['adx'] = ta.ADX(dataframe)
        
        # RSI
        dataframe['rsi'] = ta.RSI(dataframe)

        # EMA
        dataframe['ema'] = ta.EMA(dataframe['close'], timeperiod=self.ema_period.value)

        # Volume Weighted
        dataframe['volume_mean'] = dataframe['volume'].rolling(self.volume_check.value).mean().shift(1)
        dataframe['volume_mean_exit'] = dataframe['volume'].rolling(self.volume_check_exit.value).mean().shift(1)


        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:

        dataframe.loc[
            (
                        (dataframe['adx'] > self.adx_long_min.value) & # trend strength confirmation
                        (dataframe['adx'] < self.adx_long_max.value) & # trend strength confirmation
                        # (dataframe['adx'] > dataframe['adx'].shift(1)) & 
                        (dataframe['psar'] < dataframe['close']) & 
                        (dataframe['ema'] < dataframe['close']) & 
                        (dataframe['ema_4h'] < dataframe['close']) & 
                        # (dataframe['eth_ema_15m'] < dataframe['close']) & 
                        # (dataframe['btc_ema_30m'] < dataframe['close']) &  
                        # (dataframe['eth_ema_30m'] < dataframe['close']) & 
                        (dataframe['trend'] == 1) &
                        # (dataframe['ct_coral_trend'] > 0) & 
                        (dataframe['rsi'] > 50) &
                        # (dataframe['volume'] > dataframe['volume'].shift(1)) &
                        (dataframe['volume'] > dataframe['volume_mean'])

            ),
            'enter_long'] = 1

        dataframe.loc[
            (
                        (dataframe['adx'] > self.adx_short_min.value) & # trend strength confirmation
                        (dataframe['adx'] < self.adx_short_max.value) & # trend strength confirmation
                        # (dataframe['adx'] > dataframe['adx'].shift(1)) & 
                        (dataframe['psar'] > dataframe['close']) & # trend reversal confirmation
                        (dataframe['ema'] > dataframe['close']) & # trend confirmation
                        (dataframe['ema_4h'] > dataframe['close']) & 
                        # (dataframe['btc_ema_15m'] > dataframe['close']) & 
                        # (dataframe['eth_ema_15m'] > dataframe['close']) & 
                        # (dataframe['btc_ema_30m'] > dataframe['close']) & 
                        # (dataframe['eth_ema_30m'] > dataframe['close']) & 
                        (dataframe['trend'] == -1) & 
                        # (dataframe['ct_coral_trend'] < 0) & 
                        (dataframe['rsi'] < 50) & # momentum indicator
                        # (dataframe['volume'] > dataframe['volume'].shift(1)) &
                        (dataframe['volume'] > dataframe['volume_mean']) # volume weighted indicator
            ),
            'enter_short'] = 1
        
        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:

        conditions_long = []
        conditions_short = []
        dataframe.loc[:, 'exit_tag'] = ''

        exit_long = (
                (dataframe['close'] < dataframe['low'].shift(self.sell_shift.value)) &
                (dataframe['volume'] > dataframe['volume_mean_exit'])
        )

        exit_short = (
                (dataframe['close'] > dataframe['high'].shift(self.sell_shift_short.value)) &
                (dataframe['volume'] > dataframe['volume_mean_exit'])
        )


        conditions_short.append(exit_short)
        dataframe.loc[exit_short, 'exit_tag'] += 'exit_short'


        conditions_long.append(exit_long)
        dataframe.loc[exit_long, 'exit_tag'] += 'exit_long'


        if conditions_long:
            dataframe.loc[
                reduce(lambda x, y: x | y, conditions_long),
                'exit_long'] = 1

        if conditions_short:
            dataframe.loc[
                reduce(lambda x, y: x | y, conditions_short),
                'exit_short'] = 1
            
        return dataframe

    def leverage(self, pair: str, current_time: datetime, current_rate: float,
                 proposed_leverage: float, max_leverage: float, side: str,
                 **kwargs) -> float:

        return self.leverage_num.value