💬 Forum

Ichimoku

🏆 League #122 / 1944

Niwa-Yume/strategie-trading/Ichimoku.py · first seen 2026-07-16 · repo updated 2024-12-01 · ⬇ 1 download

Basics mode: spot timeframe: 4h interface version: 3
Settings stoploss: -0.75 has minimal roi custom stoploss process only new candles startup candle count: 5 hyperopt hyperopt params: 6
Indicators ATR Ichimoku pandas_ta talib
Concepts trend_following
Methods custom_stoploss
15 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 →

  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
# --- Do not remove these libs ---
import numpy as np  # noqa
import pandas as pd  # noqa
from pandas import DataFrame  # noqa
from datetime import datetime  # noqa
from typing import Optional, Union  # noqa
from freqtrade.exchange import timeframe_to_prev_date
from freqtrade.persistence import Trade
from freqtrade.strategy import (BooleanParameter, CategoricalParameter, DecimalParameter,
                                IStrategy, IntParameter)

# --------------------------------
# Add your lib to import here
import talib.abstract as ta
import pandas_ta as pta
import freqtrade.vendor.qtpylib.indicators as qtpylib


class Ichimoku(IStrategy):
    INTERFACE_VERSION = 3

    timeframe = '4h'

    USE_TALIB = False

    # Can this strategy go short?
    can_short: bool = False

    minimal_roi = {
        "0": 5000.0
    }

    stoploss = -0.75

    trailing_stop = False
    process_only_new_candles: bool = True
    use_exit_signal = True
    exit_profit_only = False
    ignore_roi_if_entry_signal = False

    use_custom_stoploss: bool = True

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

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

    # Optional order time in force.
    order_time_in_force = {
        'entry': 'gtc',
        'exit': 'gtc'
    }

    TS = IntParameter(10, 40, default=37, space="buy", optimize=True)
    KS = IntParameter(30, 120, default=79, space="buy", optimize=True)
    SS = IntParameter(60, 240, default=86, space="buy", optimize=True)

    ATR_length = IntParameter(7, 21, default=11, space="buy", optimize=True)
    ATR_Multip = DecimalParameter(1.0, 6.0, decimals=1, default=1.5, space="buy", optimize=True)
    rr = DecimalParameter(1.0, 4.0, decimals=1, default=4.0, space="buy", optimize=True)

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

        if self.dp.runmode.value in ('live', 'dry_run'):
            # use TA_LIB for backtest for performance, but avoid for live run for some possible stability issue.
            self.USE_TALIB = False
        else:
            self.USE_TALIB = True

        ichimo = pta.ichimoku(high=dataframe['high'], low=dataframe['low'], close=dataframe['close'],
                              tenkan=int(self.TS.value), kijun=int(self.KS.value), senkou=int(self.SS.value),
                              include_chikou=True)[0]
        
        dataframe['tenkan'] = ichimo[f'ITS_{int(self.TS.value)}'].copy()
        dataframe['kijun'] = ichimo[f'IKS_{int(self.KS.value)}'].copy()
        dataframe['senkanA'] = ichimo[f'ISA_{int(self.TS.value)}'].copy()
        dataframe['senkanB'] = ichimo[f'ISB_{int(self.KS.value)}'].copy()
        dataframe['chiko'] = ichimo[f'ICS_{int(self.KS.value)}'].copy()

        dataframe['ATR'] = pta.atr(dataframe['high'], dataframe['low'], dataframe['close'],
                                   length=int(self.ATR_length.value), talib=self.USE_TALIB)

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                    (dataframe['close'] > dataframe['senkanA'])
                    &
                    (dataframe['close'] > dataframe['senkanB'])
                    &
                    (dataframe['close'] > dataframe['tenkan'])
                    &
                    (dataframe['senkanB'] > dataframe['senkanA']) # "cloud is green"
                    &
                    (dataframe['tenkan'] > dataframe['kijun'])
            ),
            'enter_long'] = 1
            
        dataframe.loc[
            (
                    (dataframe['close'] < dataframe['senkanA'])
                    &
                    (dataframe['close'] < dataframe['senkanB'])
                    &
                    (dataframe['close'] < dataframe['tenkan'])
                    &
                    (dataframe['senkanB'] < dataframe['senkanA']) # "cloud is red"
                    &
                    (dataframe['tenkan'] < dataframe['kijun'])
            ),
            'enter_short'] = 1

        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                (dataframe['high'] < dataframe['tenkan'])
            ),
            'exit_long'] = 1
        dataframe.loc[
            (
                (dataframe['low'] > dataframe['tenkan'])
            ),
            'exit_short'] = 1

        return dataframe

    def custom_stoploss(self, pair: str, trade: Trade, current_time: datetime,
                        current_rate: float, current_profit: float, **kwargs) -> float:
        """
        Fonction de stop-loss personnalisée
        """
        # Récupération des données analysées pour la paire et le timeframe
        dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
        
        # Conversion de la date d'ouverture du trade au format du timeframe
        trade_date = timeframe_to_prev_date(self.timeframe, trade.open_date_utc)
        
        # Récupération de la bougie correspondant à l'ouverture du trade
        trade_candle = dataframe.loc[dataframe['date'] == trade_date]

        # Logique de Stop Loss
        c2 = False
        if not trade_candle.empty:
            trade_candle = trade_candle.squeeze()
            if not trade.is_short:
                # Pour les positions longues, le SL est placé en dessous du prix d'entrée
                c2 = current_rate < trade.open_rate - trade_candle['ATR'] * float(self.ATR_Multip.value)
            else:
                # Pour les positions courtes, le SL est placé au-dessus du prix d'entrée
                c2 = current_rate > trade.open_rate + trade_candle['ATR'] * float(self.ATR_Multip.value)
            if c2:
                return -0.0001  # Déclenche le stop-loss

        # Logique de Take Profit
        c1 = False
        if not trade_candle.empty:
            trade_candle = trade_candle.squeeze()
            dist = trade_candle['ATR'] * self.ATR_Multip.value
            if not trade.is_short:
                # Pour les positions longues, le TP est placé au-dessus du prix d'entrée
                c1 = current_rate > trade.open_rate + dist * float(self.rr.value)
            else:
                # Pour les positions courtes, le TP est placé en dessous du prix d'entrée
                c1 = current_rate < trade.open_rate - dist * float(self.rr.value)
            if c1:
                return -0.0001  # Déclenche le take-profit

        # Si aucune condition n'est remplie, retourne le stop-loss par défaut
        return self.stoploss