• 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.31
/freqtrade/freqai/RL/Base4ActionRLEnv.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
    Exit = 1
1✔
15
    Long_enter = 2
1✔
16
    Short_enter = 3
1✔
17

18

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

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

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

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

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

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

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

76
            if trade_type is not None:
1✔
77
                self.trade_history.append(
1✔
78
                    {'price': self.current_price(), 'index': self._current_tick,
79
                     'type': trade_type, 'profit': self.get_unrealized_profit()})
80

81
        if (self._total_profit < self.max_drawdown or
1✔
82
                self._total_unrealized_profit < self.max_drawdown):
83
            self._done = True
×
84

85
        self._position_history.append(self._position)
1✔
86

87
        info = dict(
1✔
88
            tick=self._current_tick,
89
            action=action,
90
            total_reward=self.total_reward,
91
            total_profit=self._total_profit,
92
            position=self._position.value,
93
            trade_duration=self.get_trade_duration(),
94
            current_profit_pct=self.get_unrealized_profit()
95
        )
96

97
        observation = self._get_observation()
1✔
98

99
        # user can play with time if they want
100
        truncated = False
1✔
101

102
        self._update_history(info)
1✔
103

104
        return observation, step_reward, self._done, truncated, info
1✔
105

106
    def is_tradesignal(self, action: int) -> bool:
1✔
107
        """
108
        Determine if the signal is a trade signal
109
        e.g.: agent wants a Actions.Long_exit while it is in a Positions.short
110
        """
111
        return not ((action == Actions.Neutral.value and self._position == Positions.Neutral) or
1✔
112
                    (action == Actions.Neutral.value and self._position == Positions.Short) or
113
                    (action == Actions.Neutral.value and self._position == Positions.Long) or
114
                    (action == Actions.Short_enter.value and self._position == Positions.Short) or
115
                    (action == Actions.Short_enter.value and self._position == Positions.Long) or
116
                    (action == Actions.Exit.value and self._position == Positions.Neutral) or
117
                    (action == Actions.Long_enter.value and self._position == Positions.Long) or
118
                    (action == Actions.Long_enter.value and self._position == Positions.Short))
119

120
    def _is_valid(self, action: int) -> bool:
1✔
121
        """
122
        Determine if the signal is valid.
123
        e.g.: agent wants a Actions.Long_exit while it is in a Positions.short
124
        """
125
        # Agent should only try to exit if it is in position
126
        if action == Actions.Exit.value:
1✔
127
            if self._position not in (Positions.Short, Positions.Long):
1✔
128
                return False
1✔
129

130
        # Agent should only try to enter if it is not in position
131
        if action in (Actions.Short_enter.value, Actions.Long_enter.value):
1✔
132
            if self._position != Positions.Neutral:
1✔
133
                return False
1✔
134

135
        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