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

freqtrade / freqtrade / 4131167254

pending completion
4131167254

push

github-actions

GitHub
Merge pull request #7983 from stash86/bt-metrics

16866 of 17748 relevant lines covered (95.03%)

0.95 hits per line

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

92.19
/freqtrade/freqai/RL/Base4ActionRLEnv.py
1
import logging
1✔
2
from enum import Enum
1✔
3

4
from gym 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])
1✔
52

53
        trade_type = None
1✔
54
        if self.is_tradesignal(action):
1✔
55
            """
56
            Action: Neutral, position: Long ->  Close Long
57
            Action: Neutral, position: Short -> Close Short
58

59
            Action: Long, position: Neutral -> Open Long
60
            Action: Long, position: Short -> Close Short and Open Long
61

62
            Action: Short, position: Neutral -> Open Short
63
            Action: Short, position: Long -> Close Long and Open Short
64
            """
65

66
            if action == Actions.Neutral.value:
1✔
67
                self._position = Positions.Neutral
×
68
                trade_type = "neutral"
×
69
                self._last_trade_tick = None
×
70
            elif action == Actions.Long_enter.value:
1✔
71
                self._position = Positions.Long
1✔
72
                trade_type = "long"
1✔
73
                self._last_trade_tick = self._current_tick
1✔
74
            elif action == Actions.Short_enter.value:
1✔
75
                self._position = Positions.Short
1✔
76
                trade_type = "short"
1✔
77
                self._last_trade_tick = self._current_tick
1✔
78
            elif action == Actions.Exit.value:
1✔
79
                self._update_total_profit()
1✔
80
                self._position = Positions.Neutral
1✔
81
                trade_type = "neutral"
1✔
82
                self._last_trade_tick = None
1✔
83
            else:
84
                print("case not defined")
×
85

86
            if trade_type is not None:
1✔
87
                self.trade_history.append(
1✔
88
                    {'price': self.current_price(), 'index': self._current_tick,
89
                     'type': trade_type})
90

91
        if (self._total_profit < self.max_drawdown or
1✔
92
                self._total_unrealized_profit < self.max_drawdown):
93
            self._done = True
×
94

95
        self._position_history.append(self._position)
1✔
96

97
        info = dict(
1✔
98
            tick=self._current_tick,
99
            action=action,
100
            total_reward=self.total_reward,
101
            total_profit=self._total_profit,
102
            position=self._position.value,
103
            trade_duration=self.get_trade_duration(),
104
            current_profit_pct=self.get_unrealized_profit()
105
        )
106

107
        observation = self._get_observation()
1✔
108

109
        self._update_history(info)
1✔
110

111
        return observation, step_reward, self._done, info
1✔
112

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

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

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

142
        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