Elffuss BraidHub

kikocis/freqtrade public

d3e2efacbd9a · 11.6 KiB · executableRawPermalink
1#!/usr/bin/env python3
2"""
3Simple command line client into RPC commands
4Can be used as an alternate to Telegram
5
6Should not import anything from freqtrade,
7so it can be used as a standalone script.
8"""
9
10import argparse
11import inspect
12import json
13import logging
14import re
15import sys
16from pathlib import Path
17from urllib.parse import urlencode, urlparse, urlunparse
18
19import rapidjson
20import requests
21from requests.exceptions import ConnectionError
22
23
24logging.basicConfig(
25 level=logging.INFO,
26 format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
27)
28logger = logging.getLogger("ft_rest_client")
29
30
31class FtRestClient():
32
33 def __init__(self, serverurl, username=None, password=None):
34
35 self._serverurl = serverurl
36 self._session = requests.Session()
37 self._session.auth = (username, password)
38
39 def _call(self, method, apipath, params: dict = None, data=None, files=None):
40
41 if str(method).upper() not in ('GET', 'POST', 'PUT', 'DELETE'):
42 raise ValueError('invalid method <{0}>'.format(method))
43 basepath = f"{self._serverurl}/api/v1/{apipath}"
44
45 hd = {"Accept": "application/json",
46 "Content-Type": "application/json"
47 }
48
49 # Split url
50 schema, netloc, path, par, query, fragment = urlparse(basepath)
51 # URLEncode query string
52 query = urlencode(params) if params else ""
53 # recombine url
54 url = urlunparse((schema, netloc, path, par, query, fragment))
55
56 try:
57 resp = self._session.request(method, url, headers=hd, data=json.dumps(data))
58 # return resp.text
59 return resp.json()
60 except ConnectionError:
61 logger.warning("Connection error")
62
63 def _get(self, apipath, params: dict = None):
64 return self._call("GET", apipath, params=params)
65
66 def _delete(self, apipath, params: dict = None):
67 return self._call("DELETE", apipath, params=params)
68
69 def _post(self, apipath, params: dict = None, data: dict = None):
70 return self._call("POST", apipath, params=params, data=data)
71
72 def start(self):
73 """Start the bot if it's in the stopped state.
74
75 :return: json object
76 """
77 return self._post("start")
78
79 def stop(self):
80 """Stop the bot. Use `start` to restart.
81
82 :return: json object
83 """
84 return self._post("stop")
85
86 def stopbuy(self):
87 """Stop buying (but handle sells gracefully). Use `reload_config` to reset.
88
89 :return: json object
90 """
91 return self._post("stopbuy")
92
93 def reload_config(self):
94 """Reload configuration.
95
96 :return: json object
97 """
98 return self._post("reload_config")
99
100 def balance(self):
101 """Get the account balance.
102
103 :return: json object
104 """
105 return self._get("balance")
106
107 def count(self):
108 """Return the amount of open trades.
109
110 :return: json object
111 """
112 return self._get("count")
113
114 def locks(self):
115 """Return current locks
116
117 :return: json object
118 """
119 return self._get("locks")
120
121 def delete_lock(self, lock_id):
122 """Delete (disable) lock from the database.
123
124 :param lock_id: ID for the lock to delete
125 :return: json object
126 """
127 return self._delete("locks/{}".format(lock_id))
128
129 def daily(self, days=None):
130 """Return the amount of open trades.
131
132 :return: json object
133 """
134 return self._get("daily", params={"timescale": days} if days else None)
135
136 def edge(self):
137 """Return information about edge.
138
139 :return: json object
140 """
141 return self._get("edge")
142
143 def profit(self):
144 """Return the profit summary.
145
146 :return: json object
147 """
148 return self._get("profit")
149
150 def stats(self):
151 """Return the stats report (durations, sell-reasons).
152
153 :return: json object
154 """
155 return self._get("stats")
156
157 def performance(self):
158 """Return the performance of the different coins.
159
160 :return: json object
161 """
162 return self._get("performance")
163
164 def status(self):
165 """Get the status of open trades.
166
167 :return: json object
168 """
169 return self._get("status")
170
171 def version(self):
172 """Return the version of the bot.
173
174 :return: json object containing the version
175 """
176 return self._get("version")
177
178 def show_config(self):
179 """
180 Returns part of the configuration, relevant for trading operations.
181 :return: json object containing the version
182 """
183 return self._get("show_config")
184
185 def ping(self):
186 """simple ping"""
187 configstatus = self.show_config()
188 if not configstatus:
189 return {"status": "not_running"}
190 elif configstatus['state'] == "running":
191 return {"status": "pong"}
192 else:
193 return {"status": "not_running"}
194
195 def logs(self, limit=None):
196 """Show latest logs.
197
198 :param limit: Limits log messages to the last <limit> logs. No limit to get all the trades.
199 :return: json object
200 """
201 return self._get("logs", params={"limit": limit} if limit else 0)
202
203 def trades(self, limit=None):
204 """Return trades history.
205
206 :param limit: Limits trades to the X last trades. No limit to get all the trades.
207 :return: json object
208 """
209 return self._get("trades", params={"limit": limit} if limit else 0)
210
211 def delete_trade(self, trade_id):
212 """Delete trade from the database.
213 Tries to close open orders. Requires manual handling of this asset on the exchange.
214
215 :param trade_id: Deletes the trade with this ID from the database.
216 :return: json object
217 """
218 return self._delete("trades/{}".format(trade_id))
219
220 def whitelist(self):
221 """Show the current whitelist.
222
223 :return: json object
224 """
225 return self._get("whitelist")
226
227 def blacklist(self, *args):
228 """Show the current blacklist.
229
230 :param add: List of coins to add (example: "BNB/BTC")
231 :return: json object
232 """
233 if not args:
234 return self._get("blacklist")
235 else:
236 return self._post("blacklist", data={"blacklist": args})
237
238 def forcebuy(self, pair, price=None):
239 """Buy an asset.
240
241 :param pair: Pair to buy (ETH/BTC)
242 :param price: Optional - price to buy
243 :return: json object of the trade
244 """
245 data = {"pair": pair,
246 "price": price
247 }
248 return self._post("forcebuy", data=data)
249
250 def forcesell(self, tradeid):
251 """Force-sell a trade.
252
253 :param tradeid: Id of the trade (can be received via status command)
254 :return: json object
255 """
256
257 return self._post("forcesell", data={"tradeid": tradeid})
258
259 def strategies(self):
260 """Lists available strategies
261
262 :return: json object
263 """
264 return self._get("strategies")
265
266 def strategy(self, strategy):
267 """Get strategy details
268
269 :param strategy: Strategy class name
270 :return: json object
271 """
272 return self._get(f"strategy/{strategy}")
273
274 def plot_config(self):
275 """Return plot configuration if the strategy defines one.
276
277 :return: json object
278 """
279 return self._get("plot_config")
280
281 def available_pairs(self, timeframe=None, stake_currency=None):
282 """Return available pair (backtest data) based on timeframe / stake_currency selection
283
284 :param timeframe: Only pairs with this timeframe available.
285 :param stake_currency: Only pairs that include this timeframe
286 :return: json object
287 """
288 return self._get("available_pairs", params={
289 "stake_currency": stake_currency if timeframe else '',
290 "timeframe": timeframe if timeframe else '',
291 })
292
293 def pair_candles(self, pair, timeframe, limit=None):
294 """Return live dataframe for <pair><timeframe>.
295
296 :param pair: Pair to get data for
297 :param timeframe: Only pairs with this timeframe available.
298 :param limit: Limit result to the last n candles.
299 :return: json object
300 """
301 return self._get("available_pairs", params={
302 "pair": pair,
303 "timeframe": timeframe,
304 "limit": limit,
305 })
306
307 def pair_history(self, pair, timeframe, strategy, timerange=None):
308 """Return historic, analyzed dataframe
309
310 :param pair: Pair to get data for
311 :param timeframe: Only pairs with this timeframe available.
312 :param strategy: Strategy to analyze and get values for
313 :param timerange: Timerange to get data for (same format than --timerange endpoints)
314 :return: json object
315 """
316 return self._get("pair_history", params={
317 "pair": pair,
318 "timeframe": timeframe,
319 "strategy": strategy,
320 "timerange": timerange if timerange else '',
321 })
322
323
324def add_arguments():
325 parser = argparse.ArgumentParser()
326 parser.add_argument("command",
327 help="Positional argument defining the command to execute.",
328 nargs="?"
329 )
330
331 parser.add_argument('--show',
332 help='Show possible methods with this client',
333 dest='show',
334 action='store_true',
335 default=False
336 )
337
338 parser.add_argument('-c', '--config',
339 help='Specify configuration file (default: %(default)s). ',
340 dest='config',
341 type=str,
342 metavar='PATH',
343 default='config.json'
344 )
345
346 parser.add_argument("command_arguments",
347 help="Positional arguments for the parameters for [command]",
348 nargs="*",
349 default=[]
350 )
351
352 args = parser.parse_args()
353 return vars(args)
354
355
356def load_config(configfile):
357 file = Path(configfile)
358 if file.is_file():
359 with file.open("r") as f:
360 config = rapidjson.load(f, parse_mode=rapidjson.PM_COMMENTS |
361 rapidjson.PM_TRAILING_COMMAS)
362 return config
363 else:
364 logger.warning(f"Could not load config file {file}.")
365 sys.exit(1)
366
367
368def print_commands():
369 # Print dynamic help for the different commands using the commands doc-strings
370 client = FtRestClient(None)
371 print("Possible commands:\n")
372 for x, y in inspect.getmembers(client):
373 if not x.startswith('_'):
374 doc = re.sub(':return:.*', '', getattr(client, x).__doc__, flags=re.MULTILINE).rstrip()
375 print(f"{x}\n\t{doc}\n")
376
377
378def main(args):
379
380 if args.get("show"):
381 print_commands()
382 sys.exit()
383
384 config = load_config(args['config'])
385 url = config.get('api_server', {}).get('server_url', '127.0.0.1')
386 port = config.get('api_server', {}).get('listen_port', '8080')
387 username = config.get('api_server', {}).get('username')
388 password = config.get('api_server', {}).get('password')
389
390 server_url = f"http://{url}:{port}"
391 client = FtRestClient(server_url, username, password)
392
393 m = [x for x, y in inspect.getmembers(client) if not x.startswith('_')]
394 command = args["command"]
395 if command not in m:
396 logger.error(f"Command {command} not defined")
397 print_commands()
398 return
399
400 print(json.dumps(getattr(client, command)(*args["command_arguments"])))
401
402
403if __name__ == "__main__":
404 args = add_arguments()
405 main(args)