-import time
-from ccxt import ExchangeError
-from store import *
-
-def move_balances(market, debug=False):
- needed_in_margin = {}
- for trade in TradeStore.all:
- if trade.trade_type == "short":
- if trade.value_to.currency not in needed_in_margin:
- needed_in_margin[trade.value_to.currency] = 0
- needed_in_margin[trade.value_to.currency] += abs(trade.value_to)
- for currency, needed in needed_in_margin.items():
- current_balance = BalanceStore.all[currency].margin_free
- delta = (needed - current_balance).value
- # FIXME: don't remove too much if there are open margin position
- if delta > 0:
- if debug:
- print("market.transfer_balance({}, {}, 'exchange', 'margin')".format(currency, delta))
- else:
- market.transfer_balance(currency, delta, "exchange", "margin")
- elif delta < 0:
- if debug:
- print("market.transfer_balance({}, {}, 'margin', 'exchange')".format(currency, -delta))
- else:
- market.transfer_balance(currency, -delta, "margin", "exchange")
-
- BalanceStore.fetch_balances(market)
-
-ticker_cache = {}
-ticker_cache_timestamp = time.time()
-def get_ticker(c1, c2, market, refresh=False):
- global ticker_cache, ticker_cache_timestamp
- def invert(ticker):
- return {
- "inverted": True,
- "average": (1/ticker["bid"] + 1/ticker["ask"]) / 2,
- "original": ticker,
- }
- def augment_ticker(ticker):
- ticker.update({
- "inverted": False,
- "average": (ticker["bid"] + ticker["ask"] ) / 2,
- })
-
- if time.time() - ticker_cache_timestamp > 5:
- ticker_cache = {}
- ticker_cache_timestamp = time.time()
- elif not refresh:
- if (c1, c2, market.__class__) in ticker_cache:
- return ticker_cache[(c1, c2, market.__class__)]
- if (c2, c1, market.__class__) in ticker_cache:
- return invert(ticker_cache[(c2, c1, market.__class__)])
-
+from datetime import datetime
+import argparse
+import configparser
+import psycopg2
+import os
+import sys
+
+import portfolio
+
+def main_parse_args(argv):
+ parser = argparse.ArgumentParser(
+ description="Run the trade bot")
+
+ parser.add_argument("-c", "--config",
+ default="config.ini",
+ required=False,
+ help="Config file to load (default: config.ini)")
+ parser.add_argument("--before",
+ default=False, action='store_const', const=True,
+ help="Run the steps before the cryptoportfolio update")
+ parser.add_argument("--after",
+ default=False, action='store_const', const=True,
+ help="Run the steps after the cryptoportfolio update")
+ parser.add_argument("--debug",
+ default=False, action='store_const', const=True,
+ help="Run in debug mode")
+ parser.add_argument("--user",
+ default=None, required=False, help="Only run for that user")
+ parser.add_argument("--action",
+ default=None, required=False,
+ help="Do a different action than trading")
+
+ args = parser.parse_args(argv)
+
+ if not os.path.exists(args.config):
+ print("no config file found, exiting")
+ sys.exit(1)
+
+ return args
+
+def main_parse_config(config_file):
+ config = configparser.ConfigParser()
+ config.read(config_file)
+
+ if "postgresql" not in config:
+ print("no configuration for postgresql in config file")
+ sys.exit(1)
+
+ if "app" in config and "report_path" in config["app"]:
+ report_path = config["app"]["report_path"]
+
+ if not os.path.exists(report_path):
+ os.makedirs(report_path)
+ else:
+ report_path = None
+
+ return [config["postgresql"], report_path]
+
+def main_fetch_markets(pg_config, user):
+ connection = psycopg2.connect(**pg_config)
+ cursor = connection.cursor()
+
+ if user is None:
+ cursor.execute("SELECT config,user_id FROM market_configs")
+ else:
+ cursor.execute("SELECT config,user_id FROM market_configs WHERE user_id = %s", user)
+
+ for row in cursor:
+ yield row
+
+def main_process_market(user_market, action, before=False, after=False):
+ if action is None:
+ if before:
+ process_sell_all__1_all_sell(user_market)
+ if after:
+ portfolio.Portfolio.wait_for_recent(user_market)
+ process_sell_all__2_all_buy(user_market)
+ elif action == "print_balances":
+ print_balances(user_market)
+ elif action == "print_orders":
+ print_orders(user_market)
+ else:
+ raise NotImplementedError("Unknown action {}".format(action))
+
+def main_store_report(report_path, user_id, user_market):