• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

freqtrade / freqtrade / 9394559170

26 Apr 2024 06:36AM UTC coverage: 94.656% (-0.02%) from 94.674%
9394559170

push

github

xmatthias
Loader should be passed as kwarg for clarity

20280 of 21425 relevant lines covered (94.66%)

0.95 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.96
/freqtrade/freqai/RL/Base5ActionRLEnv.py
1
import logging
1✔
2
from enum import Enum
1✔
3

4
from gymnasium import spaces
1✔
5

6
from freqtrade.freqai.RL.BaseEnvironment import BaseEnvironment, Positions
1✔
7

8

9
logger = logging.getLogger(__name__)
1✔
10

11

12
class Actions(Enum):
1✔
13
    Neutral = 0
1✔
14
    Long_enter = 1
1✔
15
    Long_exit = 2
1✔
16
    Short_enter = 3
1✔
17
    Short_exit = 4
1✔
18

19

20
class Base5ActionRLEnv(BaseEnvironment):
1✔
21
    """
22
    Base class for a 5 action environment
23
    """
24
    def __init__(self, **kwargs):
1✔
25
        super().__init__(**kwargs)
1✔
26
        self.actions = Actions
1✔
27

28
    def set_action_space(self):
1✔
29
        self.action_space = spaces.Discrete(len(Actions))
1✔
30

31
    def step(self, action: int):
1✔
32
        """
33
        Logic for a single step (incrementing one candle in time)
34
        by the agent
35
        :param: action: int = the action type that the agent plans
36
            to take for the current step.
37
        :returns:
38
            observation = current state of environment
39
            step_reward = the reward from `calculate_reward()`
40
            _done = if the agent "died" or if the candles finished
41
            info = dict passed back to openai gym lib
42
        """
43
        self._done = False
1✔
44
        self._current_tick += 1
1✔
45

46
        if self._current_tick == self._end_tick:
1✔
47
            self._done = True
1✔
48

49
        self._update_unrealized_total_profit()
1✔
50
        step_reward = self.calculate_reward(action)
1✔
51
        self.total_reward += step_reward
1✔
52
        self.tensorboard_log(self.actions._member_names_[action], category="actions")
1✔
53

54
        trade_type = None
1✔
55
        if self.is_tradesignal(action):
1✔
56

57
            if action == Actions.Neutral.value:
1✔
58
                self._position = Positions.Neutral
×
59
                trade_type = "neutral"
×
60
                self._last_trade_tick = None
×
61
            elif action == Actions.Long_enter.value:
1✔
62
                self._position = Positions.Long
1✔
63
                trade_type = "enter_long"
1✔
64
                self._last_trade_tick = self._current_tick
1✔
65
            elif action == Actions.Short_enter.value:
1✔
66
                self._position = Positions.Short
1✔
67
                trade_type = "enter_short"
1✔
68
                self._last_trade_tick = self._current_tick
1✔
69
            elif action == Actions.Long_exit.value:
1✔
70
                self._update_total_profit()
1✔
71
                self._position = Positions.Neutral
1✔
72
                trade_type = "exit_long"
1✔
73
                self._last_trade_tick = None
1✔
74
            elif action == Actions.Short_exit.value:
1✔
75
                self._update_total_profit()
1✔
76
                self._position = Positions.Neutral
1✔
77
                trade_type = "exit_short"
1✔
78
                self._last_trade_tick = None
1✔
79
            else:
80
                print("case not defined")
×
81

82
            if trade_type is not None:
1✔
83
                self.trade_history.append(
1✔
84
                    {'price': self.current_price(), 'index': self._current_tick,
85
                     'type': trade_type, 'profit': self.get_unrealized_profit()})
86

87
        if (self._total_profit < self.max_drawdown or
1✔
88
                self._total_unrealized_profit < self.max_drawdown):
89
            self._done = True
×
90

91
        self._position_history.append(self._position)
1✔
92

93
        info = dict(
1✔
94
            tick=self._current_tick,
95
            action=action,
96
            total_reward=self.total_reward,
97
            total_profit=self._total_profit,
98
            position=self._position.value,
99
            trade_duration=self.get_trade_duration(),
100
            current_profit_pct=self.get_unrealized_profit()
101
        )
102

103
        observation = self._get_observation()
1✔
104
        # user can play with time if they want
105
        truncated = False
1✔
106

107
        self._update_history(info)
1✔
108

109
        return observation, step_reward, self._done, truncated, info
1✔
110

111
    def is_tradesignal(self, action: int) -> bool:
1✔
112
        """
113
        Determine if the signal is a trade signal
114
        e.g.: agent wants a Actions.Long_exit while it is in a Positions.short
115
        """
116
        return not ((action == Actions.Neutral.value and self._position == Positions.Neutral) or
1✔
117
                    (action == Actions.Neutral.value and self._position == Positions.Short) or
118
                    (action == Actions.Neutral.value and self._position == Positions.Long) or
119
                    (action == Actions.Short_enter.value and self._position == Positions.Short) or
120
                    (action == Actions.Short_enter.value and self._position == Positions.Long) or
121
                    (action == Actions.Short_exit.value and self._position == Positions.Long) or
122
                    (action == Actions.Short_exit.value and self._position == Positions.Neutral) or
123
                    (action == Actions.Long_enter.value and self._position == Positions.Long) or
124
                    (action == Actions.Long_enter.value and self._position == Positions.Short) or
125
                    (action == Actions.Long_exit.value and self._position == Positions.Short) or
126
                    (action == Actions.Long_exit.value and self._position == Positions.Neutral))
127

128
    def _is_valid(self, action: int) -> bool:
1✔
129
        # trade signal
130
        """
131
        Determine if the signal is valid.
132
        e.g.: agent wants a Actions.Long_exit while it is in a Positions.short
133
        """
134
        # Agent should only try to exit if it is in position
135
        if action in (Actions.Short_exit.value, Actions.Long_exit.value):
1✔
136
            if self._position not in (Positions.Short, Positions.Long):
1✔
137
                return False
1✔
138

139
        # Agent should only try to enter if it is not in position
140
        if action in (Actions.Short_enter.value, Actions.Long_enter.value):
1✔
141
            if self._position != Positions.Neutral:
1✔
142
                return False
1✔
143

144
        return True
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc