Exemple #1
0
 def __init__(self, config: dict):
     self.exchange = 'binance_spot'
     self.balance = {}
     super().__init__(spotify_config(config))
     self.spot = self.config['spot'] = True
     self.inverse = self.config['inverse'] = False
     self.hedge_mode = self.config['hedge_mode'] = False
     self.do_shrt = self.config['do_shrt'] = self.config['shrt'][
         'enabled'] = False
     self.session = aiohttp.ClientSession()
     self.headers = {'X-MBX-APIKEY': self.key}
     self.base_endpoint = ''
     self.force_update_interval = 40
Exemple #2
0
async def main():
    parser = argparse.ArgumentParser(prog='Backtest', description='Backtest given passivbot config.')
    parser.add_argument('live_config_path', type=str, help='path to live config to test')
    parser = add_argparse_args(parser)
    parser.add_argument(
        "-lw",
        "--long_wallet_exposure_limit",
        "--long-wallet-exposure-limit",
        type=float,
        required=False,
        dest="long_wallet_exposure_limit",
        default=None,
        help="specify long wallet exposure limit, overriding value from live config",
    )
    parser.add_argument(
        "-sw",
        "--short_wallet_exposure_limit",
        "--short-wallet-exposure-limit",
        type=float,
        required=False,
        dest="short_wallet_exposure_limit",
        default=None,
        help="specify short wallet exposure limit, overriding value from live config",
    )

    args = parser.parse_args()
    config = await prepare_backtest_config(args)
    live_config = load_live_config(args.live_config_path)
    config.update(live_config)

    if args.long_wallet_exposure_limit is not None:
        print(
            f"overriding long wallet exposure limit ({config['long']['pbr_limit']}) "
            f"with new value: {args.long_wallet_exposure_limit}"
        )
        config["long"]["pbr_limit"] = args.long_wallet_exposure_limit
    if args.short_wallet_exposure_limit is not None:
        print(
            f"overriding short wallet exposure limit ({config['shrt']['pbr_limit']}) "
            f"with new value: {args.short_wallet_exposure_limit}"
        )
        config["shrt"]["pbr_limit"] = args.short_wallet_exposure_limit

    if 'spot' in config['market_type']:
        live_config = spotify_config(live_config)
    downloader = Downloader(config)
    print()
    for k in (keys := ['exchange', 'spot', 'symbol', 'market_type', 'config_type', 'starting_balance', 'start_date', 'end_date',
                       'latency_simulation_ms']):
        if k in config:
            print(f"{k: <{max(map(len, keys)) + 2}} {config[k]}")
Exemple #3
0
 def __init__(self, config: dict):
     if config["exchange"] == "binance_us":
         self.exchange = "binance_us"
     else:
         self.exchange = "binance_spot"
     self.balance = {}
     super().__init__(spotify_config(config))
     self.spot = self.config["spot"] = True
     self.inverse = self.config["inverse"] = False
     self.hedge_mode = self.config["hedge_mode"] = False
     self.do_short = self.config["do_short"] = self.config["short"][
         "enabled"] = False
     self.session = aiohttp.ClientSession()
     self.headers = {"X-MBX-APIKEY": self.key}
     self.base_endpoint = ""
     self.force_update_interval = 40
Exemple #4
0
async def main() -> None:
    parser = argparse.ArgumentParser(prog='passivbot',
                                     description='run passivbot')
    parser.add_argument('user',
                        type=str,
                        help='user/account_name defined in api-keys.json')
    parser.add_argument('symbol', type=str, help='symbol to trade')
    parser.add_argument('live_config_path',
                        type=str,
                        help='live config to use')
    parser.add_argument(
        '-m',
        '--market_type',
        type=str,
        required=False,
        dest='market_type',
        default=None,
        help=
        'specify whether spot or futures (default), overriding value from backtest config'
    )
    parser.add_argument('-gs',
                        '--graceful_stop',
                        action='store_true',
                        help='if true, disable long and short')
    parser.add_argument(
        "-lw",
        "--long_wallet_exposure_limit",
        "--long-wallet-exposure-limit",
        type=float,
        required=False,
        dest="long_wallet_exposure_limit",
        default=None,
        help=
        "specify long wallet exposure limit, overriding value from live config",
    )
    parser.add_argument(
        "-sw",
        "--short_wallet_exposure_limit",
        "--short-wallet-exposure-limit",
        type=float,
        required=False,
        dest="short_wallet_exposure_limit",
        default=None,
        help=
        "specify short wallet exposure limit, overriding value from live config",
    )
    parser.add_argument(
        "-sm",
        "--short_mode",
        "--short-mode",
        type=str,
        required=False,
        dest="short_mode",
        default=None,
        help=
        "specify one of following short modes: [n (normal), m (manual), gs (graceful_stop), p (panic), t (tp_only)]"
    )
    parser.add_argument(
        "-lm",
        "--long_mode",
        "--long-mode",
        type=str,
        required=False,
        dest="long_mode",
        default=None,
        help=
        "specify one of following long modes: [n (normal), m (manual), gs (graceful_stop), p (panic), t (tp_only)]"
    )
    parser.add_argument('-ab',
                        '--assigned_balance',
                        type=float,
                        required=False,
                        dest='assigned_balance',
                        default=None,
                        help='add assigned_balance to live config')

    args = parser.parse_args()
    try:
        accounts = json.load(open('api-keys.json'))
    except Exception as e:
        print(e, 'failed to load api-keys.json file')
        return
    try:
        account = accounts[args.user]
    except Exception as e:
        print('unrecognized account name', args.user, e)
        return
    try:
        config = load_live_config(args.live_config_path)
    except Exception as e:
        print(e, 'failed to load config', args.live_config_path)
        return
    config['user'] = args.user
    config['exchange'] = account['exchange']
    config['symbol'] = args.symbol
    config['live_config_path'] = args.live_config_path
    config[
        'market_type'] = args.market_type if args.market_type is not None else 'futures'
    if args.assigned_balance is not None:
        print(f'\nassigned balance set to {args.assigned_balance}\n')
        config['assigned_balance'] = args.assigned_balance

    if args.long_mode is not None:
        if args.long_mode in ['gs', 'graceful_stop', 'graceful-stop']:
            print(
                '\n\nlong graceful stop enabled; will not make new entries once existing positions are closed\n'
            )
            config['long']['enabled'] = config['do_long'] = False
        elif args.long_mode in ['m', 'manual']:
            print(
                '\n\nlong manual mode enabled; will neither cancel nor create long orders'
            )
            config['long_mode'] = 'manual'
        elif args.long_mode in ['n', 'normal']:
            print('\n\nlong normal mode')
            config['long']['enabled'] = config['do_long'] = True
        elif args.long_mode in ['p', 'panic']:
            print('\nlong panic mode enabled')
            config['long_mode'] = 'panic'
            config['long']['enabled'] = config['do_long'] = False
        elif args.long_mode.lower() in ['t', 'tp_only', 'tp-only']:
            print('\nlong tp only mode enabled')
            config['long_mode'] = 'tp_only'
    if args.short_mode is not None:
        if args.short_mode in ['gs', 'graceful_stop', 'graceful-stop']:
            print(
                '\n\nshrt graceful stop enabled; will not make new entries once existing positions are closed\n'
            )
            config['shrt']['enabled'] = config['do_shrt'] = False
        elif args.short_mode in ['m', 'manual']:
            print(
                '\n\nshrt manual mode enabled; will neither cancel nor create shrt orders'
            )
            config['shrt_mode'] = 'manual'
        elif args.short_mode in ['n', 'normal']:
            print('\n\nshrt normal mode')
            config['shrt']['enabled'] = config['do_shrt'] = True
        elif args.short_mode in ['p', 'panic']:
            print('\nshort panic mode enabled')
            config['shrt_mode'] = 'panic'
            config['shrt']['enabled'] = config['do_shrt'] = False
        elif args.short_mode.lower() in ['t', 'tp_only', 'tp-only']:
            print('\nshort tp only mode enabled')
            config['shrt_mode'] = 'tp_only'
    if args.graceful_stop:
        print(
            '\n\ngraceful stop enabled for both long and short; will not make new entries once existing positions are closed\n'
        )
        config['long']['enabled'] = config['do_long'] = False
        config['shrt']['enabled'] = config['do_shrt'] = False

    if args.long_wallet_exposure_limit is not None:
        print(
            f"overriding long wallet exposure limit ({config['long']['pbr_limit']}) "
            f"with new value: {args.long_wallet_exposure_limit}")
        config["long"]["pbr_limit"] = args.long_wallet_exposure_limit
    if args.short_wallet_exposure_limit is not None:
        print(
            f"overriding short wallet exposure limit ({config['shrt']['pbr_limit']}) "
            f"with new value: {args.short_wallet_exposure_limit}")
        config["shrt"]["pbr_limit"] = args.short_wallet_exposure_limit

    if 'spot' in config['market_type']:
        config = spotify_config(config)

    if account['exchange'] == 'binance':
        if 'spot' in config['market_type']:
            from procedures import create_binance_bot_spot
            bot = await create_binance_bot_spot(config)
        else:
            from procedures import create_binance_bot
            bot = await create_binance_bot(config)
    elif account['exchange'] == 'bybit':
        from procedures import create_bybit_bot
        bot = await create_bybit_bot(config)
    else:
        raise Exception('unknown exchange', account['exchange'])

    print('using config')
    pprint.pprint(denumpyize(config))

    signal.signal(signal.SIGINT, bot.stop)
    signal.signal(signal.SIGTERM, bot.stop)
    await start_bot(bot)
    await bot.session.close()
Exemple #5
0
async def main():
    parser = argparse.ArgumentParser(
        prog="Backtest", description="Backtest given passivbot config.")
    parser.add_argument("live_config_path",
                        type=str,
                        help="path to live config to test")
    parser = add_argparse_args(parser)
    parser.add_argument(
        "-lw",
        "--long_wallet_exposure_limit",
        "--long-wallet-exposure-limit",
        type=float,
        required=False,
        dest="long_wallet_exposure_limit",
        default=None,
        help=
        "specify long wallet exposure limit, overriding value from live config",
    )
    parser.add_argument(
        "-sw",
        "--short_wallet_exposure_limit",
        "--short-wallet-exposure-limit",
        type=float,
        required=False,
        dest="short_wallet_exposure_limit",
        default=None,
        help=
        "specify short wallet exposure limit, overriding value from live config",
    )
    parser.add_argument(
        "-le",
        "--long_enabled",
        "--long-enabled",
        type=str,
        required=False,
        dest="long_enabled",
        default=None,
        help="specify long enabled [y/n], overriding value from live config",
    )
    parser.add_argument(
        "-se",
        "--short_enabled",
        "--short-enabled",
        type=str,
        required=False,
        dest="short_enabled",
        default=None,
        help="specify short enabled [y/n], overriding value from live config",
    )
    parser.add_argument(
        "-np",
        "--n_parts",
        "--n-parts",
        type=int,
        required=False,
        dest="n_parts",
        default=None,
        help="set n backtest slices to plot",
    )
    parser.add_argument(
        "-oh",
        "--ohlcv",
        help="use 1m ohlcv instead of 1s ticks",
        action="store_true",
    )
    args = parser.parse_args()
    if args.symbol is None:
        tmp_cfg = load_hjson_config(args.backtest_config_path)
        symbols = (tmp_cfg["symbol"] if type(tmp_cfg["symbol"]) == list else
                   tmp_cfg["symbol"].split(","))
    else:
        symbols = args.symbol.split(",")
    for symbol in symbols:
        args = parser.parse_args()
        args.symbol = symbol
        config = await prepare_backtest_config(args)
        config["n_parts"] = args.n_parts
        live_config = load_live_config(args.live_config_path)
        config.update(live_config)

        if args.long_wallet_exposure_limit is not None:
            print(
                f"overriding long wallet exposure limit ({config['long']['wallet_exposure_limit']}) "
                f"with new value: {args.long_wallet_exposure_limit}")
            config["long"][
                "wallet_exposure_limit"] = args.long_wallet_exposure_limit
        if args.short_wallet_exposure_limit is not None:
            print(
                f"overriding short wallet exposure limit ({config['short']['wallet_exposure_limit']}) "
                f"with new value: {args.short_wallet_exposure_limit}")
            config["short"][
                "wallet_exposure_limit"] = args.short_wallet_exposure_limit
        if args.long_enabled is not None:
            config["long"]["enabled"] = "y" in args.long_enabled.lower()
        if args.short_enabled is not None:
            config["short"]["enabled"] = "y" in args.short_enabled.lower()
        if "spot" in config["market_type"]:
            live_config = spotify_config(live_config)
        config["ohlcv"] = args.ohlcv

        print()
        for k in (keys := [
                "exchange",
                "spot",
                "symbol",
                "market_type",
                "passivbot_mode",
                "config_type",
                "starting_balance",
                "start_date",
                "end_date",
                "latency_simulation_ms",
                "base_dir",
        ]):
            if k in config:
                print(f"{k: <{max(map(len, keys)) + 2}} {config[k]}")
        print()
        if config["ohlcv"]:
            data = load_hlc_cache(
                symbol,
                config["start_date"],
                config["end_date"],
                base_dir=config["base_dir"],
                spot=config["spot"],
            )
        else:
            downloader = Downloader(config)
            data = await downloader.get_sampled_ticks()
        config["n_days"] = round_(
            (data[-1][0] - data[0][0]) / (1000 * 60 * 60 * 24), 0.1)
        pprint.pprint(denumpyize(live_config))
        plot_wrap(config, data)
Exemple #6
0
async def main() -> None:
    parser = argparse.ArgumentParser(prog="passivbot",
                                     description="run passivbot")
    parser.add_argument("user",
                        type=str,
                        help="user/account_name defined in api-keys.json")
    parser.add_argument("symbol", type=str, help="symbol to trade")
    parser.add_argument("live_config_path",
                        type=str,
                        help="live config to use")
    parser.add_argument(
        "-m",
        "--market_type",
        type=str,
        required=False,
        dest="market_type",
        default=None,
        help=
        "specify whether spot or futures (default), overriding value from backtest config",
    )
    parser.add_argument(
        "-gs",
        "--graceful_stop",
        action="store_true",
        help="if true, disable long and short",
    )
    parser.add_argument(
        "-lw",
        "--long_wallet_exposure_limit",
        "--long-wallet-exposure-limit",
        type=float,
        required=False,
        dest="long_wallet_exposure_limit",
        default=None,
        help=
        "specify long wallet exposure limit, overriding value from live config",
    )
    parser.add_argument(
        "-sw",
        "--short_wallet_exposure_limit",
        "--short-wallet-exposure-limit",
        type=float,
        required=False,
        dest="short_wallet_exposure_limit",
        default=None,
        help=
        "specify short wallet exposure limit, overriding value from live config",
    )
    parser.add_argument(
        "-sm",
        "--short_mode",
        "--short-mode",
        type=str,
        required=False,
        dest="short_mode",
        default=None,
        help=
        "specify one of following short modes: [n (normal), m (manual), gs (graceful_stop), p (panic), t (tp_only)]",
    )
    parser.add_argument(
        "-lm",
        "--long_mode",
        "--long-mode",
        type=str,
        required=False,
        dest="long_mode",
        default=None,
        help=
        "specify one of following long modes: [n (normal), m (manual), gs (graceful_stop), p (panic), t (tp_only)]",
    )
    parser.add_argument(
        "-ab",
        "--assigned_balance",
        type=float,
        required=False,
        dest="assigned_balance",
        default=None,
        help="add assigned_balance to live config",
    )

    args = parser.parse_args()
    try:
        accounts = json.load(open("api-keys.json"))
    except Exception as e:
        print(e, "failed to load api-keys.json file")
        return
    try:
        account = accounts[args.user]
    except Exception as e:
        print("unrecognized account name", args.user, e)
        return
    try:
        config = load_live_config(args.live_config_path)
    except Exception as e:
        print(e, "failed to load config", args.live_config_path)
        return
    config["user"] = args.user
    config["exchange"] = account["exchange"]
    config["symbol"] = args.symbol
    config[
        "market_type"] = args.market_type if args.market_type is not None else "futures"
    config["passivbot_mode"] = determine_passivbot_mode(config)
    if args.assigned_balance is not None:
        print(f"\nassigned balance set to {args.assigned_balance}\n")
        config["assigned_balance"] = args.assigned_balance

    if args.long_mode is None:
        if not config["long"]["enabled"]:
            config["long_mode"] = "manual"
    else:
        if args.long_mode in ["gs", "graceful_stop", "graceful-stop"]:
            print(
                "\n\nlong graceful stop enabled; will not make new entries once existing positions are closed\n"
            )
            config["long"]["enabled"] = config["do_long"] = False
        elif args.long_mode in ["m", "manual"]:
            print(
                "\n\nlong manual mode enabled; will neither cancel nor create long orders"
            )
            config["long_mode"] = "manual"
        elif args.long_mode in ["n", "normal"]:
            print("\n\nlong normal mode")
            config["long"]["enabled"] = config["do_long"] = True
        elif args.long_mode in ["p", "panic"]:
            print("\nlong panic mode enabled")
            config["long_mode"] = "panic"
            config["long"]["enabled"] = config["do_long"] = False
        elif args.long_mode.lower() in ["t", "tp_only", "tp-only"]:
            print("\nlong tp only mode enabled")
            config["long_mode"] = "tp_only"
    if args.short_mode is None:
        if not config["short"]["enabled"]:
            config["short_mode"] = "manual"
    else:
        if args.short_mode in ["gs", "graceful_stop", "graceful-stop"]:
            print(
                "\n\nshort graceful stop enabled; will not make new entries once existing positions are closed\n"
            )
            config["short"]["enabled"] = config["do_short"] = False
        elif args.short_mode in ["m", "manual"]:
            print(
                "\n\nshort manual mode enabled; will neither cancel nor create short orders"
            )
            config["short_mode"] = "manual"
        elif args.short_mode in ["n", "normal"]:
            print("\n\nshort normal mode")
            config["short"]["enabled"] = config["do_short"] = True
        elif args.short_mode in ["p", "panic"]:
            print("\nshort panic mode enabled")
            config["short_mode"] = "panic"
            config["short"]["enabled"] = config["do_short"] = False
        elif args.short_mode.lower() in ["t", "tp_only", "tp-only"]:
            print("\nshort tp only mode enabled")
            config["short_mode"] = "tp_only"
    if args.graceful_stop:
        print(
            "\n\ngraceful stop enabled for both long and short; will not make new entries once existing positions are closed\n"
        )
        config["long"]["enabled"] = config["do_long"] = False
        config["short"]["enabled"] = config["do_short"] = False
        config["long_mode"] = None
        config["short_mode"] = None

    if args.long_wallet_exposure_limit is not None:
        print(
            f"overriding long wallet exposure limit ({config['long']['wallet_exposure_limit']}) "
            f"with new value: {args.long_wallet_exposure_limit}")
        config["long"][
            "wallet_exposure_limit"] = args.long_wallet_exposure_limit
    if args.short_wallet_exposure_limit is not None:
        print(
            f"overriding short wallet exposure limit ({config['short']['wallet_exposure_limit']}) "
            f"with new value: {args.short_wallet_exposure_limit}")
        config["short"][
            "wallet_exposure_limit"] = args.short_wallet_exposure_limit

    if "spot" in config["market_type"]:
        config = spotify_config(config)

    if account["exchange"] == "binance":
        if "spot" in config["market_type"]:
            from procedures import create_binance_bot_spot

            bot = await create_binance_bot_spot(config)
        else:
            from procedures import create_binance_bot

            bot = await create_binance_bot(config)
    elif account["exchange"] == "binance_us":
        from procedures import create_binance_bot_spot

        bot = await create_binance_bot_spot(config)
    elif account["exchange"] == "bybit":
        from procedures import create_bybit_bot

        bot = await create_bybit_bot(config)
    else:
        raise Exception("unknown exchange", account["exchange"])

    print("using config")
    pprint.pprint(denumpyize(config))
    signal.signal(signal.SIGINT, bot.stop)
    signal.signal(signal.SIGTERM, bot.stop)
    await start_bot(bot)
    await bot.session.close()