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

freqtrade / freqtrade / 6181253459

08 Sep 2023 06:04AM UTC coverage: 94.614% (+0.06%) from 94.556%
6181253459

push

github-actions

web-flow
Merge pull request #9159 from stash86/fix-adjust

remove old codes when we only can do partial entries

2 of 2 new or added lines in 1 file covered. (100.0%)

19114 of 20202 relevant lines covered (94.61%)

0.95 hits per line

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

98.02
/freqtrade/commands/deploy_commands.py
1
import logging
1✔
2
import sys
1✔
3
from pathlib import Path
1✔
4
from typing import Any, Dict, Optional, Tuple
1✔
5

6
import requests
1✔
7

8
from freqtrade.configuration import setup_utils_configuration
1✔
9
from freqtrade.configuration.directory_operations import copy_sample_files, create_userdata_dir
1✔
10
from freqtrade.constants import USERPATH_STRATEGIES
1✔
11
from freqtrade.enums import RunMode
1✔
12
from freqtrade.exceptions import OperationalException
1✔
13
from freqtrade.util import render_template, render_template_with_fallback
1✔
14

15

16
logger = logging.getLogger(__name__)
1✔
17

18

19
def start_create_userdir(args: Dict[str, Any]) -> None:
1✔
20
    """
21
    Create "user_data" directory to contain user data strategies, hyperopt, ...)
22
    :param args: Cli args from Arguments()
23
    :return: None
24
    """
25
    if "user_data_dir" in args and args["user_data_dir"]:
1✔
26
        userdir = create_userdata_dir(args["user_data_dir"], create_dir=True)
1✔
27
        copy_sample_files(userdir, overwrite=args["reset"])
1✔
28
    else:
29
        logger.warning("`create-userdir` requires --userdir to be set.")
1✔
30
        sys.exit(1)
1✔
31

32

33
def deploy_new_strategy(strategy_name: str, strategy_path: Path, subtemplate: str) -> None:
1✔
34
    """
35
    Deploy new strategy from template to strategy_path
36
    """
37
    fallback = 'full'
1✔
38
    attributes = render_template_with_fallback(
1✔
39
        templatefile=f"strategy_subtemplates/strategy_attributes_{subtemplate}.j2",
40
        templatefallbackfile=f"strategy_subtemplates/strategy_attributes_{fallback}.j2",
41
    )
42
    indicators = render_template_with_fallback(
1✔
43
        templatefile=f"strategy_subtemplates/indicators_{subtemplate}.j2",
44
        templatefallbackfile=f"strategy_subtemplates/indicators_{fallback}.j2",
45
    )
46
    buy_trend = render_template_with_fallback(
1✔
47
        templatefile=f"strategy_subtemplates/buy_trend_{subtemplate}.j2",
48
        templatefallbackfile=f"strategy_subtemplates/buy_trend_{fallback}.j2",
49
    )
50
    sell_trend = render_template_with_fallback(
1✔
51
        templatefile=f"strategy_subtemplates/sell_trend_{subtemplate}.j2",
52
        templatefallbackfile=f"strategy_subtemplates/sell_trend_{fallback}.j2",
53
    )
54
    plot_config = render_template_with_fallback(
1✔
55
        templatefile=f"strategy_subtemplates/plot_config_{subtemplate}.j2",
56
        templatefallbackfile=f"strategy_subtemplates/plot_config_{fallback}.j2",
57
    )
58
    additional_methods = render_template_with_fallback(
1✔
59
        templatefile=f"strategy_subtemplates/strategy_methods_{subtemplate}.j2",
60
        templatefallbackfile="strategy_subtemplates/strategy_methods_empty.j2",
61
    )
62

63
    strategy_text = render_template(templatefile='base_strategy.py.j2',
1✔
64
                                    arguments={"strategy": strategy_name,
65
                                               "attributes": attributes,
66
                                               "indicators": indicators,
67
                                               "buy_trend": buy_trend,
68
                                               "sell_trend": sell_trend,
69
                                               "plot_config": plot_config,
70
                                               "additional_methods": additional_methods,
71
                                               })
72

73
    logger.info(f"Writing strategy to `{strategy_path}`.")
1✔
74
    strategy_path.write_text(strategy_text)
1✔
75

76

77
def start_new_strategy(args: Dict[str, Any]) -> None:
1✔
78

79
    config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
1✔
80

81
    if "strategy" in args and args["strategy"]:
1✔
82

83
        new_path = config['user_data_dir'] / USERPATH_STRATEGIES / (args['strategy'] + '.py')
1✔
84

85
        if new_path.exists():
1✔
86
            raise OperationalException(f"`{new_path}` already exists. "
1✔
87
                                       "Please choose another Strategy Name.")
88

89
        deploy_new_strategy(args['strategy'], new_path, args['template'])
1✔
90

91
    else:
92
        raise OperationalException("`new-strategy` requires --strategy to be set.")
1✔
93

94

95
def clean_ui_subdir(directory: Path):
1✔
96
    if directory.is_dir():
1✔
97
        logger.info("Removing UI directory content.")
1✔
98

99
        for p in reversed(list(directory.glob('**/*'))):  # iterate contents from leaves to root
1✔
100
            if p.name in ('.gitkeep', 'fallback_file.html'):
1✔
101
                continue
1✔
102
            if p.is_file():
1✔
103
                p.unlink()
1✔
104
            elif p.is_dir():
1✔
105
                p.rmdir()
1✔
106

107

108
def read_ui_version(dest_folder: Path) -> Optional[str]:
1✔
109
    file = dest_folder / '.uiversion'
1✔
110
    if not file.is_file():
1✔
111
        return None
1✔
112

113
    with file.open('r') as f:
1✔
114
        return f.read()
1✔
115

116

117
def download_and_install_ui(dest_folder: Path, dl_url: str, version: str):
1✔
118
    from io import BytesIO
1✔
119
    from zipfile import ZipFile
1✔
120

121
    logger.info(f"Downloading {dl_url}")
1✔
122
    resp = requests.get(dl_url).content
1✔
123
    dest_folder.mkdir(parents=True, exist_ok=True)
1✔
124
    with ZipFile(BytesIO(resp)) as zf:
1✔
125
        for fn in zf.filelist:
1✔
126
            with zf.open(fn) as x:
1✔
127
                destfile = dest_folder / fn.filename
1✔
128
                if fn.is_dir():
1✔
129
                    destfile.mkdir(exist_ok=True)
1✔
130
                else:
131
                    destfile.write_bytes(x.read())
1✔
132
    with (dest_folder / '.uiversion').open('w') as f:
1✔
133
        f.write(version)
1✔
134

135

136
def get_ui_download_url(version: Optional[str] = None) -> Tuple[str, str]:
1✔
137
    base_url = 'https://api.github.com/repos/freqtrade/frequi/'
1✔
138
    # Get base UI Repo path
139

140
    resp = requests.get(f"{base_url}releases")
1✔
141
    resp.raise_for_status()
1✔
142
    r = resp.json()
1✔
143

144
    if version:
1✔
145
        tmp = [x for x in r if x['name'] == version]
1✔
146
        if tmp:
1✔
147
            latest_version = tmp[0]['name']
1✔
148
            assets = tmp[0].get('assets', [])
1✔
149
        else:
150
            raise ValueError("UI-Version not found.")
1✔
151
    else:
152
        latest_version = r[0]['name']
1✔
153
        assets = r[0].get('assets', [])
1✔
154
    dl_url = ''
1✔
155
    if assets and len(assets) > 0:
1✔
156
        dl_url = assets[0]['browser_download_url']
1✔
157

158
    # URL not found - try assets url
159
    if not dl_url:
1✔
160
        assets = r[0]['assets_url']
1✔
161
        resp = requests.get(assets)
1✔
162
        r = resp.json()
1✔
163
        dl_url = r[0]['browser_download_url']
1✔
164

165
    return dl_url, latest_version
1✔
166

167

168
def start_install_ui(args: Dict[str, Any]) -> None:
1✔
169

170
    dest_folder = Path(__file__).parents[1] / 'rpc/api_server/ui/installed/'
1✔
171
    # First make sure the assets are removed.
172
    dl_url, latest_version = get_ui_download_url(args.get('ui_version'))
1✔
173

174
    curr_version = read_ui_version(dest_folder)
1✔
175
    if curr_version == latest_version and not args.get('erase_ui_only'):
1✔
176
        logger.info(f"UI already up-to-date, FreqUI Version {curr_version}.")
×
177
        return
×
178

179
    clean_ui_subdir(dest_folder)
1✔
180
    if args.get('erase_ui_only'):
1✔
181
        logger.info("Erased UI directory content. Not downloading new version.")
1✔
182
    else:
183
        # Download a new version
184
        download_and_install_ui(dest_folder, dl_url, latest_version)
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