freqtrade-client 2024.3.dev0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.1
2
+ Name: freqtrade-client
3
+ Version: 2024.3.dev0
4
+ Summary: Freqtrade - Client scripts
5
+ Author: Freqtrade Team
6
+ Author-email: Freqtrade Team <freqtrade@protonmail.com>
7
+ License: GPLv3
8
+ Project-URL: Homepage, https://github.com/freqtrade/freqtrade
9
+ Project-URL: Documentation, https://freqtrade.io
10
+ Project-URL: Bug Tracker, https://github.com/freqtrade/freqtrade/issues
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Operating System :: MacOS
19
+ Classifier: Operating System :: Unix
20
+ Classifier: Topic :: Office/Business :: Financial :: Investment
21
+ Requires-Python: >=3.9
22
+ Requires-Dist: requests>=2.26.0
23
+ Requires-Dist: python-rapidjson>=1.0
@@ -0,0 +1,27 @@
1
+ from freqtrade_client.ft_rest_client import FtRestClient
2
+
3
+
4
+ __all__ = ['FtRestClient']
5
+
6
+
7
+ __version__ = '2024.3-dev0'
8
+
9
+ if 'dev' in __version__:
10
+ from pathlib import Path
11
+ try:
12
+ import subprocess
13
+ freqtrade_basedir = Path(__file__).parent
14
+
15
+ __version__ = __version__ + '-' + subprocess.check_output(
16
+ ['git', 'log', '--format="%h"', '-n 1'],
17
+ stderr=subprocess.DEVNULL, cwd=freqtrade_basedir).decode("utf-8").rstrip().strip('"')
18
+
19
+ except Exception: # pragma: no cover
20
+ # git not available, ignore
21
+ try:
22
+ # Try Fallback to freqtrade_commit file (created by CI while building docker image)
23
+ versionfile = Path('./freqtrade_commit')
24
+ if versionfile.is_file():
25
+ __version__ = f"docker-{__version__}-{versionfile.read_text()[:8]}"
26
+ except Exception:
27
+ pass
@@ -0,0 +1,106 @@
1
+ import argparse
2
+ import inspect
3
+ import json
4
+ import logging
5
+ import re
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Any, Dict
9
+
10
+ import rapidjson
11
+ from freqtrade_client import __version__
12
+ from freqtrade_client.ft_rest_client import FtRestClient
13
+
14
+
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
18
+ )
19
+ logger = logging.getLogger("ft_rest_client")
20
+
21
+
22
+ def add_arguments():
23
+ parser = argparse.ArgumentParser()
24
+ parser.add_argument("command",
25
+ help="Positional argument defining the command to execute.",
26
+ nargs="?"
27
+ )
28
+ parser.add_argument('-V', '--version', action='version', version=f'%(prog)s {__version__}')
29
+ parser.add_argument('--show',
30
+ help='Show possible methods with this client',
31
+ dest='show',
32
+ action='store_true',
33
+ default=False
34
+ )
35
+
36
+ parser.add_argument('-c', '--config',
37
+ help='Specify configuration file (default: %(default)s). ',
38
+ dest='config',
39
+ type=str,
40
+ metavar='PATH',
41
+ default='config.json'
42
+ )
43
+
44
+ parser.add_argument("command_arguments",
45
+ help="Positional arguments for the parameters for [command]",
46
+ nargs="*",
47
+ default=[]
48
+ )
49
+
50
+ args = parser.parse_args()
51
+ return vars(args)
52
+
53
+
54
+ def load_config(configfile):
55
+ file = Path(configfile)
56
+ if file.is_file():
57
+ with file.open("r") as f:
58
+ config = rapidjson.load(f, parse_mode=rapidjson.PM_COMMENTS |
59
+ rapidjson.PM_TRAILING_COMMAS)
60
+ return config
61
+ else:
62
+ logger.warning(f"Could not load config file {file}.")
63
+ sys.exit(1)
64
+
65
+
66
+ def print_commands():
67
+ # Print dynamic help for the different commands using the commands doc-strings
68
+ client = FtRestClient(None)
69
+ print("Possible commands:\n")
70
+ for x, y in inspect.getmembers(client):
71
+ if not x.startswith('_'):
72
+ doc = re.sub(':return:.*', '', getattr(client, x).__doc__, flags=re.MULTILINE).rstrip()
73
+ print(f"{x}\n\t{doc}\n")
74
+
75
+
76
+ def main_exec(args: Dict[str, Any]):
77
+
78
+ if args.get("show"):
79
+ print_commands()
80
+ sys.exit()
81
+
82
+ config = load_config(args['config'])
83
+ url = config.get('api_server', {}).get('listen_ip_address', '127.0.0.1')
84
+ port = config.get('api_server', {}).get('listen_port', '8080')
85
+ username = config.get('api_server', {}).get('username')
86
+ password = config.get('api_server', {}).get('password')
87
+
88
+ server_url = f"http://{url}:{port}"
89
+ client = FtRestClient(server_url, username, password)
90
+
91
+ m = [x for x, y in inspect.getmembers(client) if not x.startswith('_')]
92
+ command = args["command"]
93
+ if command not in m:
94
+ logger.error(f"Command {command} not defined")
95
+ print_commands()
96
+ return
97
+
98
+ print(json.dumps(getattr(client, command)(*args["command_arguments"])))
99
+
100
+
101
+ def main():
102
+ """
103
+ Main entry point for the client
104
+ """
105
+ args = add_arguments()
106
+ main_exec(args)
@@ -0,0 +1,417 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Simple command line client into RPC commands
4
+ Can be used as an alternate to Telegram
5
+
6
+ Should not import anything from freqtrade,
7
+ so it can be used as a standalone script.
8
+ """
9
+
10
+ import json
11
+ import logging
12
+ from typing import Optional
13
+ from urllib.parse import urlencode, urlparse, urlunparse
14
+
15
+ import requests
16
+ from requests.exceptions import ConnectionError
17
+
18
+
19
+ logger = logging.getLogger("ft_rest_client")
20
+
21
+
22
+ class FtRestClient:
23
+
24
+ def __init__(self, serverurl, username=None, password=None):
25
+
26
+ self._serverurl = serverurl
27
+ self._session = requests.Session()
28
+ self._session.auth = (username, password)
29
+
30
+ def _call(self, method, apipath, params: Optional[dict] = None, data=None, files=None):
31
+
32
+ if str(method).upper() not in ('GET', 'POST', 'PUT', 'DELETE'):
33
+ raise ValueError(f'invalid method <{method}>')
34
+ basepath = f"{self._serverurl}/api/v1/{apipath}"
35
+
36
+ hd = {"Accept": "application/json",
37
+ "Content-Type": "application/json"
38
+ }
39
+
40
+ # Split url
41
+ schema, netloc, path, par, query, fragment = urlparse(basepath)
42
+ # URLEncode query string
43
+ query = urlencode(params) if params else ""
44
+ # recombine url
45
+ url = urlunparse((schema, netloc, path, par, query, fragment))
46
+
47
+ try:
48
+ resp = self._session.request(method, url, headers=hd, data=json.dumps(data))
49
+ # return resp.text
50
+ return resp.json()
51
+ except ConnectionError:
52
+ logger.warning("Connection error")
53
+
54
+ def _get(self, apipath, params: Optional[dict] = None):
55
+ return self._call("GET", apipath, params=params)
56
+
57
+ def _delete(self, apipath, params: Optional[dict] = None):
58
+ return self._call("DELETE", apipath, params=params)
59
+
60
+ def _post(self, apipath, params: Optional[dict] = None, data: Optional[dict] = None):
61
+ return self._call("POST", apipath, params=params, data=data)
62
+
63
+ def start(self):
64
+ """Start the bot if it's in the stopped state.
65
+
66
+ :return: json object
67
+ """
68
+ return self._post("start")
69
+
70
+ def stop(self):
71
+ """Stop the bot. Use `start` to restart.
72
+
73
+ :return: json object
74
+ """
75
+ return self._post("stop")
76
+
77
+ def stopbuy(self):
78
+ """Stop buying (but handle sells gracefully). Use `reload_config` to reset.
79
+
80
+ :return: json object
81
+ """
82
+ return self._post("stopbuy")
83
+
84
+ def reload_config(self):
85
+ """Reload configuration.
86
+
87
+ :return: json object
88
+ """
89
+ return self._post("reload_config")
90
+
91
+ def balance(self):
92
+ """Get the account balance.
93
+
94
+ :return: json object
95
+ """
96
+ return self._get("balance")
97
+
98
+ def count(self):
99
+ """Return the amount of open trades.
100
+
101
+ :return: json object
102
+ """
103
+ return self._get("count")
104
+
105
+ def entries(self, pair=None):
106
+ """Returns List of dicts containing all Trades, based on buy tag performance
107
+ Can either be average for all pairs or a specific pair provided
108
+
109
+ :return: json object
110
+ """
111
+ return self._get("entries", params={"pair": pair} if pair else None)
112
+
113
+ def exits(self, pair=None):
114
+ """Returns List of dicts containing all Trades, based on exit reason performance
115
+ Can either be average for all pairs or a specific pair provided
116
+
117
+ :return: json object
118
+ """
119
+ return self._get("exits", params={"pair": pair} if pair else None)
120
+
121
+ def mix_tags(self, pair=None):
122
+ """Returns List of dicts containing all Trades, based on entry_tag + exit_reason performance
123
+ Can either be average for all pairs or a specific pair provided
124
+
125
+ :return: json object
126
+ """
127
+ return self._get("mix_tags", params={"pair": pair} if pair else None)
128
+
129
+ def locks(self):
130
+ """Return current locks
131
+
132
+ :return: json object
133
+ """
134
+ return self._get("locks")
135
+
136
+ def delete_lock(self, lock_id):
137
+ """Delete (disable) lock from the database.
138
+
139
+ :param lock_id: ID for the lock to delete
140
+ :return: json object
141
+ """
142
+ return self._delete(f"locks/{lock_id}")
143
+
144
+ def daily(self, days=None):
145
+ """Return the profits for each day, and amount of trades.
146
+
147
+ :return: json object
148
+ """
149
+ return self._get("daily", params={"timescale": days} if days else None)
150
+
151
+ def weekly(self, weeks=None):
152
+ """Return the profits for each week, and amount of trades.
153
+
154
+ :return: json object
155
+ """
156
+ return self._get("weekly", params={"timescale": weeks} if weeks else None)
157
+
158
+ def monthly(self, months=None):
159
+ """Return the profits for each month, and amount of trades.
160
+
161
+ :return: json object
162
+ """
163
+ return self._get("monthly", params={"timescale": months} if months else None)
164
+
165
+ def edge(self):
166
+ """Return information about edge.
167
+
168
+ :return: json object
169
+ """
170
+ return self._get("edge")
171
+
172
+ def profit(self):
173
+ """Return the profit summary.
174
+
175
+ :return: json object
176
+ """
177
+ return self._get("profit")
178
+
179
+ def stats(self):
180
+ """Return the stats report (durations, sell-reasons).
181
+
182
+ :return: json object
183
+ """
184
+ return self._get("stats")
185
+
186
+ def performance(self):
187
+ """Return the performance of the different coins.
188
+
189
+ :return: json object
190
+ """
191
+ return self._get("performance")
192
+
193
+ def status(self):
194
+ """Get the status of open trades.
195
+
196
+ :return: json object
197
+ """
198
+ return self._get("status")
199
+
200
+ def version(self):
201
+ """Return the version of the bot.
202
+
203
+ :return: json object containing the version
204
+ """
205
+ return self._get("version")
206
+
207
+ def show_config(self):
208
+ """ Returns part of the configuration, relevant for trading operations.
209
+ :return: json object containing the version
210
+ """
211
+ return self._get("show_config")
212
+
213
+ def ping(self):
214
+ """simple ping"""
215
+ configstatus = self.show_config()
216
+ if not configstatus:
217
+ return {"status": "not_running"}
218
+ elif configstatus['state'] == "running":
219
+ return {"status": "pong"}
220
+ else:
221
+ return {"status": "not_running"}
222
+
223
+ def logs(self, limit=None):
224
+ """Show latest logs.
225
+
226
+ :param limit: Limits log messages to the last <limit> logs. No limit to get the entire log.
227
+ :return: json object
228
+ """
229
+ return self._get("logs", params={"limit": limit} if limit else 0)
230
+
231
+ def trades(self, limit=None, offset=None):
232
+ """Return trades history, sorted by id
233
+
234
+ :param limit: Limits trades to the X last trades. Max 500 trades.
235
+ :param offset: Offset by this amount of trades.
236
+ :return: json object
237
+ """
238
+ params = {}
239
+ if limit:
240
+ params['limit'] = limit
241
+ if offset:
242
+ params['offset'] = offset
243
+ return self._get("trades", params)
244
+
245
+ def trade(self, trade_id):
246
+ """Return specific trade
247
+
248
+ :param trade_id: Specify which trade to get.
249
+ :return: json object
250
+ """
251
+ return self._get(f"trade/{trade_id}")
252
+
253
+ def delete_trade(self, trade_id):
254
+ """Delete trade from the database.
255
+ Tries to close open orders. Requires manual handling of this asset on the exchange.
256
+
257
+ :param trade_id: Deletes the trade with this ID from the database.
258
+ :return: json object
259
+ """
260
+ return self._delete(f"trades/{trade_id}")
261
+
262
+ def cancel_open_order(self, trade_id):
263
+ """Cancel open order for trade.
264
+
265
+ :param trade_id: Cancels open orders for this trade.
266
+ :return: json object
267
+ """
268
+ return self._delete(f"trades/{trade_id}/open-order")
269
+
270
+ def whitelist(self):
271
+ """Show the current whitelist.
272
+
273
+ :return: json object
274
+ """
275
+ return self._get("whitelist")
276
+
277
+ def blacklist(self, *args):
278
+ """Show the current blacklist.
279
+
280
+ :param add: List of coins to add (example: "BNB/BTC")
281
+ :return: json object
282
+ """
283
+ if not args:
284
+ return self._get("blacklist")
285
+ else:
286
+ return self._post("blacklist", data={"blacklist": args})
287
+
288
+ def forcebuy(self, pair, price=None):
289
+ """Buy an asset.
290
+
291
+ :param pair: Pair to buy (ETH/BTC)
292
+ :param price: Optional - price to buy
293
+ :return: json object of the trade
294
+ """
295
+ data = {"pair": pair,
296
+ "price": price
297
+ }
298
+ return self._post("forcebuy", data=data)
299
+
300
+ def forceenter(self, pair, side, price=None):
301
+ """Force entering a trade
302
+
303
+ :param pair: Pair to buy (ETH/BTC)
304
+ :param side: 'long' or 'short'
305
+ :param price: Optional - price to buy
306
+ :return: json object of the trade
307
+ """
308
+ data = {"pair": pair,
309
+ "side": side,
310
+ }
311
+ if price:
312
+ data['price'] = price
313
+ return self._post("forceenter", data=data)
314
+
315
+ def forceexit(self, tradeid, ordertype=None, amount=None):
316
+ """Force-exit a trade.
317
+
318
+ :param tradeid: Id of the trade (can be received via status command)
319
+ :param ordertype: Order type to use (must be market or limit)
320
+ :param amount: Amount to sell. Full sell if not given
321
+ :return: json object
322
+ """
323
+
324
+ return self._post("forceexit", data={
325
+ "tradeid": tradeid,
326
+ "ordertype": ordertype,
327
+ "amount": amount,
328
+ })
329
+
330
+ def strategies(self):
331
+ """Lists available strategies
332
+
333
+ :return: json object
334
+ """
335
+ return self._get("strategies")
336
+
337
+ def strategy(self, strategy):
338
+ """Get strategy details
339
+
340
+ :param strategy: Strategy class name
341
+ :return: json object
342
+ """
343
+ return self._get(f"strategy/{strategy}")
344
+
345
+ def pairlists_available(self):
346
+ """Lists available pairlist providers
347
+
348
+ :return: json object
349
+ """
350
+ return self._get("pairlists/available")
351
+
352
+ def plot_config(self):
353
+ """Return plot configuration if the strategy defines one.
354
+
355
+ :return: json object
356
+ """
357
+ return self._get("plot_config")
358
+
359
+ def available_pairs(self, timeframe=None, stake_currency=None):
360
+ """Return available pair (backtest data) based on timeframe / stake_currency selection
361
+
362
+ :param timeframe: Only pairs with this timeframe available.
363
+ :param stake_currency: Only pairs that include this timeframe
364
+ :return: json object
365
+ """
366
+ return self._get("available_pairs", params={
367
+ "stake_currency": stake_currency if timeframe else '',
368
+ "timeframe": timeframe if timeframe else '',
369
+ })
370
+
371
+ def pair_candles(self, pair, timeframe, limit=None):
372
+ """Return live dataframe for <pair><timeframe>.
373
+
374
+ :param pair: Pair to get data for
375
+ :param timeframe: Only pairs with this timeframe available.
376
+ :param limit: Limit result to the last n candles.
377
+ :return: json object
378
+ """
379
+ params = {
380
+ "pair": pair,
381
+ "timeframe": timeframe,
382
+ }
383
+ if limit:
384
+ params['limit'] = limit
385
+ return self._get("pair_candles", params=params)
386
+
387
+ def pair_history(self, pair, timeframe, strategy, timerange=None, freqaimodel=None):
388
+ """Return historic, analyzed dataframe
389
+
390
+ :param pair: Pair to get data for
391
+ :param timeframe: Only pairs with this timeframe available.
392
+ :param strategy: Strategy to analyze and get values for
393
+ :param freqaimodel: FreqAI model to use for analysis
394
+ :param timerange: Timerange to get data for (same format than --timerange endpoints)
395
+ :return: json object
396
+ """
397
+ return self._get("pair_history", params={
398
+ "pair": pair,
399
+ "timeframe": timeframe,
400
+ "strategy": strategy,
401
+ "freqaimodel": freqaimodel,
402
+ "timerange": timerange if timerange else '',
403
+ })
404
+
405
+ def sysinfo(self):
406
+ """Provides system information (CPU, RAM usage)
407
+
408
+ :return: json object
409
+ """
410
+ return self._get("sysinfo")
411
+
412
+ def health(self):
413
+ """Provides a quick health check of the running bot.
414
+
415
+ :return: json object
416
+ """
417
+ return self._get("health")
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.1
2
+ Name: freqtrade-client
3
+ Version: 2024.3.dev0
4
+ Summary: Freqtrade - Client scripts
5
+ Author: Freqtrade Team
6
+ Author-email: Freqtrade Team <freqtrade@protonmail.com>
7
+ License: GPLv3
8
+ Project-URL: Homepage, https://github.com/freqtrade/freqtrade
9
+ Project-URL: Documentation, https://freqtrade.io
10
+ Project-URL: Bug Tracker, https://github.com/freqtrade/freqtrade/issues
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Operating System :: MacOS
19
+ Classifier: Operating System :: Unix
20
+ Classifier: Topic :: Office/Business :: Financial :: Investment
21
+ Requires-Python: >=3.9
22
+ Requires-Dist: requests>=2.26.0
23
+ Requires-Dist: python-rapidjson>=1.0
@@ -0,0 +1,10 @@
1
+ pyproject.toml
2
+ freqtrade_client/__init__.py
3
+ freqtrade_client/ft_client.py
4
+ freqtrade_client/ft_rest_client.py
5
+ freqtrade_client.egg-info/PKG-INFO
6
+ freqtrade_client.egg-info/SOURCES.txt
7
+ freqtrade_client.egg-info/dependency_links.txt
8
+ freqtrade_client.egg-info/entry_points.txt
9
+ freqtrade_client.egg-info/requires.txt
10
+ freqtrade_client.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ft_rest = freqtrade_client.ft_client:main
@@ -0,0 +1,2 @@
1
+ requests>=2.26.0
2
+ python-rapidjson>=1.0
@@ -0,0 +1,54 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 64.0.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "freqtrade-client"
7
+ dynamic = ["version"]
8
+
9
+ authors = [
10
+ {name = "Freqtrade Team"},
11
+ {name = "Freqtrade Team", email = "freqtrade@protonmail.com"},
12
+ ]
13
+
14
+ description = "Freqtrade - Client scripts"
15
+ # readme = "README.md"
16
+ requires-python = ">=3.9"
17
+ license = {text = "GPLv3"}
18
+ # license = "GPLv3"
19
+ classifiers = [
20
+ "Environment :: Console",
21
+ "Intended Audience :: Science/Research",
22
+ "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Operating System :: MacOS",
28
+ "Operating System :: Unix",
29
+ "Topic :: Office/Business :: Financial :: Investment",
30
+ ]
31
+
32
+ dependencies = [
33
+ 'requests >= 2.26.0',
34
+ 'python-rapidjson >= 1.0',
35
+ ]
36
+
37
+
38
+ [project.urls]
39
+ Homepage = "https://github.com/freqtrade/freqtrade"
40
+ Documentation = "https://freqtrade.io"
41
+ "Bug Tracker" = "https://github.com/freqtrade/freqtrade/issues"
42
+
43
+
44
+ [project.scripts]
45
+ ft_rest = "freqtrade_client.ft_client:main"
46
+
47
+ [tool.setuptools.packages.find]
48
+ where = ["."]
49
+ include = ["freqtrade_client*"]
50
+ exclude = ["tests", "tests.*"]
51
+ namespaces = true
52
+
53
+ [tool.setuptools.dynamic]
54
+ version = {attr = "freqtrade_client.__version__"}
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+