def setUp(self):
     self.clock: Clock = Clock(ClockMode.BACKTEST,
                               start_time=self.start_time,
                               end_time=self.end_time)
     self.order_book_loader: HuobiOrderBookLoader = HuobiOrderBookLoader(
         "btcusdt", "btc", "usdt")
     self.order_book: OrderBook = self.order_book_loader.order_book
     self.clock.add_iterator(self.order_book_loader)
Esempio n. 2
0
 def setUp(self):
     self.clock: Clock = Clock(ClockMode.BACKTEST,
                               start_time=self.start_time,
                               end_time=self.end_time)
     self.order_book_loader: BinanceOrderBookLoaderV2 = BinanceOrderBookLoaderV2(
         "BTCUSDT", "BTC", "USDT")
     self.order_book: OrderBook = self.order_book_loader.order_book
     self.clock.add_iterator(self.order_book_loader)
 def setUp(self):
     self.weth_dai_data = DDEXOrderBookLoader("WETH-DAI", "WETH", "DAI")
     self.clock = Clock(ClockMode.BACKTEST, 1.0, self.start.timestamp(), self.end.timestamp())
     self.market = BacktestMarket()
     self.market.add_data(self.weth_dai_data)
     self.market.set_balance("WETH", 200.0)
     self.market.set_balance("DAI", 20000.0)
     self.clock.add_iterator(self.market)
Esempio n. 4
0
async def main():
    cmd_args = CmdlineParser().parse_args()
    with open(cmd_args.key_file, "r") as fd:
        encrypted_json: Dict[str, any] = json.load(fd)

    wallet: Web3Wallet = Web3Wallet(
        Account.decrypt(encrypted_json, getpass.getpass("Wallet password: "******"createdAt"], o["id"], o["marketId"]) for o in orders],
            columns=["Created", "OrderID", "Symbol"])
        order_data.Created = order_data.Created.astype(
            "datetime64[ms]").astype("datetime64[ns, UTC]")
        order_data = order_data.set_index("Created")

        while True:
            try:
                sample_ids: List[str] = list(order_data.sample(10).OrderID)
                tasks: List[asyncio.Future] = [
                    market.get_order(order_id) for order_id in sample_ids
                ]
                response_data: List[Dict[str,
                                         any]] = await asyncio.gather(*tasks)

                mismatches: int = 0
                for expected_id, response in zip(sample_ids, response_data):
                    returned_order_id = response["id"]
                    if returned_order_id != expected_id:
                        print(
                            f"    - Error: requested for {expected_id} but got {returned_order_id} back."
                        )
                        mismatches += 1

                if mismatches < 1:
                    print(
                        f"[{str(pd.Timestamp.utcnow())}] All fetches passed.")
                else:
                    print(
                        f"[{str(pd.Timestamp.utcnow())}] {mismatches} out of 10 requests failed."
                    )

                now: float = time.time()
                next_tick: float = now // 1 + 1
                await asyncio.sleep(next_tick - now)
            except asyncio.CancelledError:
                raise
Esempio n. 5
0
 def setUp(self):
     #self.weth_dai_data = DDEXOrderBookLoader("WETH-DAI", "WETH", "DAI")
     self.pair_data = BinanceOrderBookLoaderV2(self.market_name, "ETH",
                                               "USDT")
     #self.pair_data = HuobiOrderBookLoader(self.market_name, "", "")
     self.clock = Clock(ClockMode.BACKTEST, 1.0, self.start.timestamp(),
                        self.end.timestamp())
     self.market = BacktestMarket()
     #self.market.add_data(self.weth_dai_data)
     self.market.add_data(self.pair_data)
     self.market.set_balance(self.quote, 200.0)
     self.market.set_balance(self.base, 20000.0)
     self.clock.add_iterator(self.market)
Esempio n. 6
0
    def setUp(self):
        self.clock: Clock = Clock(ClockMode.BACKTEST, 1.0, self.start_timestamp, self.end_timestamp)
        self.maker_market: BacktestMarket = BacktestMarket()
        self.taker_market: BacktestMarket = BacktestMarket()
        self.maker_data: MockOrderBookLoader = MockOrderBookLoader(*self.maker_symbols)
        self.taker_data: MockOrderBookLoader = MockOrderBookLoader(*self.taker_symbols)
        self.maker_data.set_balanced_order_book(1.0, 0.5, 1.5, 0.01, 10)
        self.taker_data.set_balanced_order_book(1.0, 0.5, 1.5, 0.001, 3)
        self.maker_market.add_data(self.maker_data)
        self.taker_market.add_data(self.taker_data)
        self.maker_market.set_balance("COINALPHA", 5)
        self.maker_market.set_balance("WETH", 5)
        self.taker_market.set_balance("COINALPHA", 5)
        self.taker_market.set_balance("ETH", 5)
        self.maker_market.set_quantization_param(
            QuantizationParams(
                self.maker_symbols[0], 5, 5, 5, 5
            )
        )
        self.taker_market.set_quantization_param(
            QuantizationParams(
                self.taker_symbols[0], 5, 5, 5, 5
            )
        )

        self.market_pair: CrossExchangeMarketPair = CrossExchangeMarketPair(
            *(
                [self.maker_market] + self.maker_symbols +
                [self.taker_market] + self.taker_symbols +
                [2]
            )
        )

        logging_options: int = (CrossExchangeMarketMakingStrategy.OPTION_LOG_ALL &
                                (~CrossExchangeMarketMakingStrategy.OPTION_LOG_NULL_ORDER_SIZE))
        self.strategy: CrossExchangeMarketMakingStrategy = CrossExchangeMarketMakingStrategy(
            [self.market_pair],
            0.003,
            order_size_portfolio_ratio_limit=0.3,
            logging_options=logging_options
        )
        self.clock.add_iterator(self.maker_market)
        self.clock.add_iterator(self.taker_market)
        self.clock.add_iterator(self.strategy)

        self.maker_order_fill_logger: EventLogger = EventLogger()
        self.taker_order_fill_logger: EventLogger = EventLogger()
        self.cancel_order_logger: EventLogger = EventLogger()
        self.maker_market.add_listener(MarketEvent.OrderFilled, self.maker_order_fill_logger)
        self.taker_market.add_listener(MarketEvent.OrderFilled, self.taker_order_fill_logger)
        self.maker_market.add_listener(MarketEvent.OrderCancelled, self.cancel_order_logger)
Esempio n. 7
0
def main():
    # Define the data cache path.
    hummingsim.set_data_path(os.path.join(os.environ["PWD"], "data"))

    # Define the parameters for the backtest.
    start = pd.Timestamp("2018-12-12", tz="UTC")
    end = pd.Timestamp("2019-01-12", tz="UTC")
    binance_symbol = ("ETHUSDT", "ETH", "USDT")
    ddex_symbol = ("WETH-DAI", "WETH", "DAI")

    binance_market = BacktestMarket()
    ddex_market = BacktestMarket()
    binance_market.config = MarketConfig(AssetType.BASE_CURRENCY, 0.001,
                                         AssetType.QUOTE_CURRENCY, 0.001, {})
    ddex_market.config = MarketConfig(AssetType.BASE_CURRENCY, 0.001,
                                      AssetType.QUOTE_CURRENCY, 0.001, {})
    binance_loader = BinanceOrderBookLoaderV2(*binance_symbol)
    ddex_loader = DDEXOrderBookLoader(*ddex_symbol)

    binance_market.add_data(binance_loader)
    ddex_market.add_data(ddex_loader)

    binance_market.set_quantization_param(
        QuantizationParams("ETHUSDT", 5, 3, 5, 3))
    ddex_market.set_quantization_param(
        QuantizationParams("WETH-DAI", 5, 3, 5, 3))

    market_pair = CrossExchangeMarketPair(*([ddex_market] + list(ddex_symbol) +
                                            [binance_market] +
                                            list(binance_symbol)))
    strategy = CrossExchangeMarketMakingStrategy(
        [market_pair],
        0.003,
        logging_options=CrossExchangeMarketMakingStrategy.
        OPTION_LOG_MAKER_ORDER_FILLED)

    clock = Clock(ClockMode.BACKTEST,
                  start_time=start.timestamp(),
                  end_time=end.timestamp())
    clock.add_iterator(binance_market)
    clock.add_iterator(ddex_market)
    clock.add_iterator(strategy)

    binance_market.set_balance("ETH", 10.0)
    binance_market.set_balance("USDT", 1000.0)
    ddex_market.set_balance("WETH", 10.0)
    ddex_market.set_balance("DAI", 1000.0)

    clock.backtest()
    binance_loader.close()
    ddex_loader.close()
Esempio n. 8
0
    def setUp(self):
        self.clock: Clock = Clock(ClockMode.BACKTEST, 1.0, self.start_timestamp, self.end_timestamp)
        self.market_1: BacktestMarket = BacktestMarket()
        self.market_2: BacktestMarket = BacktestMarket()
        self.market_1_data: MockOrderBookLoader = MockOrderBookLoader(*self.market_1_symbols)
        self.market_2_data: MockOrderBookLoader = MockOrderBookLoader(*self.market_2_symbols)
        self.market_1_data.set_balanced_order_book(1.0, 0.5, 1.5, 0.01, 10)
        self.market_2_data.set_balanced_order_book(1.3, 0.5, 1.5, 0.001, 4)

        self.market_1.add_data(self.market_1_data)
        self.market_2.add_data(self.market_2_data)

        self.market_1.set_balance("COINALPHA", 5)
        self.market_1.set_balance("ETH", 5)

        self.market_2.set_balance("COINALPHA", 5)
        self.market_2.set_balance("WETH", 5)

        self.market_1.set_quantization_param(
            QuantizationParams(
                self.market_1_symbols[0], 5, 5, 5, 5
            )
        )
        self.market_2.set_quantization_param(
            QuantizationParams(
                self.market_2_symbols[0], 5, 5, 5, 5
            )
        )
        self.market_pair: ArbitrageMarketPair = ArbitrageMarketPair(
            *(
                [self.market_1] + self.market_1_symbols + [self.market_2] + self.market_2_symbols
            )
        )

        logging_options: int = ArbitrageStrategy.OPTION_LOG_ALL
        self.strategy: ArbitrageStrategy = ArbitrageStrategy(
            [self.market_pair],
            min_profitability=0.01
        )
        self.logging_options = logging_options
        self.clock.add_iterator(self.market_1)
        self.clock.add_iterator(self.market_2)
        self.clock.add_iterator(self.strategy)

        self.market_1_order_fill_logger: EventLogger = EventLogger()
        self.market_2_order_fill_logger: EventLogger = EventLogger()

        self.market_1.add_listener(MarketEvent.OrderFilled, self.market_1_order_fill_logger)
        self.market_2.add_listener(MarketEvent.OrderFilled, self.market_2_order_fill_logger)
 def setUpClass(cls):
     cls.clock: Clock = Clock(ClockMode.REALTIME)
     cls.wallet = Web3Wallet(private_key=conf.web3_private_key_radar,
                             backend_urls=conf.test_web3_provider_list,
                             erc20_token_addresses=[conf.mn_zerox_token_address, conf.mn_weth_token_address],
                             chain=EthereumChain.MAIN_NET)
     cls.market: RadarRelayMarket = RadarRelayMarket(wallet=cls.wallet,
                                                     web3_url=conf.test_web3_provider_list[0],
                                                     order_book_tracker_data_source_type=
                                                         OrderBookTrackerDataSourceType.EXCHANGE_API,
                                                     symbols=["ZRX-WETH"])
     print("Initializing Radar Relay market... ")
     cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()
     cls.clock.add_iterator(cls.wallet)
     cls.clock.add_iterator(cls.market)
     cls.ev_loop.run_until_complete(cls.clock.run_til(time.time() + 1))
     cls.ev_loop.run_until_complete(cls.wait_til_ready())
     print("Ready.")
    def setUpClass(cls):
        global MAINNET_RPC_URL

        cls.clock: Clock = Clock(ClockMode.REALTIME)
        cls.market: BinanceMarket = BinanceMarket(
            MAINNET_RPC_URL,
            conf.binance_api_key,
            conf.binance_api_secret,
            order_book_tracker_data_source_type=OrderBookTrackerDataSourceType.
            EXCHANGE_API,
            user_stream_tracker_data_source_type=UserStreamTrackerDataSourceType
            .EXCHANGE_API,
            symbols=["ZRXETH", "LOOMETH"])
        print("Initializing Binance market... this will take about a minute.")
        cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()
        cls.clock.add_iterator(cls.market)
        cls.ev_loop.run_until_complete(cls.clock.run_til(time.time() + 1))
        cls.ev_loop.run_until_complete(cls.wait_til_ready())
        print("Ready.")
Esempio n. 11
0
    def setUpClass(cls):
        cls.clock: Clock = Clock(ClockMode.REALTIME)
        cls.erc20_token_address = conf.test_erc20_token_address
        cls.w3 = Web3(Web3.HTTPProvider(conf.test_web3_provider_list[0]))

        cls.wallet_a = Web3Wallet(conf.web3_test_private_key_a,
                                  conf.test_web3_provider_list,
                                  [cls.erc20_token_address])
        cls.wallet_b = Web3Wallet(conf.web3_test_private_key_b,
                                  conf.test_web3_provider_list,
                                  [cls.erc20_token_address])

        cls.erc20_token: ERC20Token = list(
            cls.wallet_a.current_backend.erc20_tokens.values())[0]

        cls.clock.add_iterator(cls.wallet_a)
        cls.clock.add_iterator(cls.wallet_b)
        cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()

        next_iteration = (time.time() // 5.0 + 1) * 5
        cls.ev_loop.run_until_complete(cls.clock.run_til(next_iteration))
def ddex_printout():
    wethdai_data: DDEXOrderBookLoader = DDEXOrderBookLoader("WETH-DAI", "WETH", "DAI")
    market: Market = BacktestMarket()
    market.add_data(wethdai_data)

    market.set_balance("ETH", 20.0)

    print("Beginning Balance:", market.get_all_balances())

    start: pd.Timestamp = pd.Timestamp("2018-12-01", tz="UTC")
    end: pd.Timestamp = pd.Timestamp("2018-12-02", tz="UTC")
    clock: Clock = Clock(ClockMode.BACKTEST, 600.0, start.timestamp(), end.timestamp())

    print_out_strategy: PrintOutStrategy2 = PrintOutStrategy2(market)
    clock.add_iterator(market)
    clock.add_iterator(print_out_strategy)
    clock.backtest()

    print("End Balance:", market.get_all_balances())

    wethdai_data.close()
def bittrex_printout():
    ethusdt_data: BittrexOrderBookLoader = BittrexOrderBookLoader("USDT-ETH", "ETH", "USDT")
    trxeth_data: BittrexOrderBookLoader = BittrexOrderBookLoader("ETH-TRX", "TRX", "ETH")
    market: Market = BacktestMarket()
    market.add_data(trxeth_data)
    market.add_data(ethusdt_data)
    market.set_balance("ETH", 20.0)
    market.set_balance("TRX", 0.0)
    print("Beginning Balance:", market.get_all_balances())

    start: pd.Timestamp = pd.Timestamp("2018-12-11", tz="UTC")
    end: pd.Timestamp = pd.Timestamp("2018-12-12", tz="UTC")
    clock: Clock = Clock(ClockMode.BACKTEST, 600.0, start.timestamp(), end.timestamp())

    print_out_strategy: PrintOutStrategy2 = PrintOutStrategy2(market)
    clock.add_iterator(market)
    clock.add_iterator(print_out_strategy)
    clock.backtest()

    print("End Balance:", market.get_all_balances())
    ethusdt_data.close()
    trxeth_data.close()
Esempio n. 14
0
 def setUpClass(cls):
     cls.clock: Clock = Clock(ClockMode.REALTIME)
     cls.market: CoinbaseProMarket = CoinbaseProMarket(
         web3_url=conf.test_web3_provider_list[0],
         coinbase_pro_api_key=conf.coinbase_pro_api_key,
         coinbase_pro_secret_key=conf.coinbase_pro_secret_key,
         coinbase_pro_passphrase=conf.coinbase_pro_passphrase,
         symbols=["ETH-USDC", "ETH-USD"])
     cls.wallet: Web3Wallet = Web3Wallet(
         private_key=conf.web3_private_key_coinbase_pro,
         backend_urls=conf.test_web3_provider_list,
         erc20_token_addresses=[
             conf.mn_weth_token_address, conf.mn_zerox_token_address
         ],
         chain=EthereumChain.MAIN_NET)
     print(
         "Initializing Coinbase Pro market... this will take about a minute."
     )
     cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()
     cls.clock.add_iterator(cls.market)
     cls.clock.add_iterator(cls.wallet)
     cls.ev_loop.run_until_complete(cls.clock.run_til(time.time() + 1))
     cls.ev_loop.run_until_complete(cls.wait_til_ready())
     print("Ready.")
Esempio n. 15
0
    async def start_market_making(self, strategy_name: str):
        strategy_cm = get_strategy_config_map(strategy_name)
        if strategy_name == "cross_exchange_market_making":
            maker_market = strategy_cm.get("maker_market").value.lower()
            taker_market = strategy_cm.get("taker_market").value.lower()
            raw_maker_symbol = strategy_cm.get(
                "maker_market_symbol").value.upper()
            raw_taker_symbol = strategy_cm.get(
                "taker_market_symbol").value.upper()
            min_profitability = strategy_cm.get("min_profitability").value
            trade_size_override = strategy_cm.get("trade_size_override").value
            strategy_report_interval = global_config_map.get(
                "strategy_report_interval").value
            limit_order_min_expiration = strategy_cm.get(
                "limit_order_min_expiration").value
            cancel_order_threshold = strategy_cm.get(
                "cancel_order_threshold").value
            active_order_canceling = strategy_cm.get(
                "active_order_canceling").value
            top_depth_tolerance_rules = [(re.compile(re_str), value)
                                         for re_str, value in strategy_cm.get(
                                             "top_depth_tolerance").value]
            top_depth_tolerance = 0.0

            for regex, tolerance_value in top_depth_tolerance_rules:
                if regex.match(raw_maker_symbol) is not None:
                    top_depth_tolerance = tolerance_value

            try:
                maker_assets: Tuple[str, str] = SymbolSplitter.split(
                    maker_market, raw_maker_symbol)
                taker_assets: Tuple[str, str] = SymbolSplitter.split(
                    taker_market, raw_taker_symbol)
            except ValueError as e:
                self.app.log(str(e))
                return

            market_names: List[Tuple[str,
                                     str]] = [(maker_market, raw_maker_symbol),
                                              (taker_market, raw_taker_symbol)]

            self._initialize_wallet(
                token_symbols=list(set(maker_assets + taker_assets)))
            self._initialize_markets(market_names)

            self.market_pair = CrossExchangeMarketPair(
                *([self.markets[maker_market], raw_maker_symbol] +
                  list(maker_assets) +
                  [self.markets[taker_market], raw_taker_symbol] +
                  list(taker_assets) + [top_depth_tolerance]))

            strategy_logging_options = (
                CrossExchangeMarketMakingStrategy.OPTION_LOG_CREATE_ORDER
                | CrossExchangeMarketMakingStrategy.OPTION_LOG_ADJUST_ORDER |
                CrossExchangeMarketMakingStrategy.OPTION_LOG_MAKER_ORDER_FILLED
                | CrossExchangeMarketMakingStrategy.OPTION_LOG_REMOVING_ORDER
                | CrossExchangeMarketMakingStrategy.OPTION_LOG_STATUS_REPORT |
                CrossExchangeMarketMakingStrategy.OPTION_LOG_MAKER_ORDER_HEDGED
            )

            self.strategy = CrossExchangeMarketMakingStrategy(
                market_pairs=[self.market_pair],
                min_profitability=min_profitability,
                status_report_interval=strategy_report_interval,
                logging_options=strategy_logging_options,
                trade_size_override=trade_size_override,
                limit_order_min_expiration=limit_order_min_expiration,
                cancel_order_threshold=cancel_order_threshold,
                active_order_canceling=active_order_canceling)

        elif strategy_name == "arbitrage":
            primary_market = strategy_cm.get("primary_market").value.lower()
            secondary_market = strategy_cm.get(
                "secondary_market").value.lower()
            raw_primary_symbol = strategy_cm.get(
                "primary_market_symbol").value.upper()
            raw_secondary_symbol = strategy_cm.get(
                "secondary_market_symbol").value.upper()
            min_profitability = strategy_cm.get("min_profitability").value
            try:
                primary_assets: Tuple[str, str] = SymbolSplitter.split(
                    primary_market, raw_primary_symbol)
                secondary_assets: Tuple[str, str] = SymbolSplitter.split(
                    secondary_market, raw_secondary_symbol)

            except ValueError as e:
                self.app.log(str(e))
                return

            market_names: List[Tuple[str, str]] = [
                (primary_market, raw_primary_symbol),
                (secondary_market, raw_secondary_symbol)
            ]
            self._initialize_wallet(
                token_symbols=list(set(primary_assets + secondary_assets)))

            self._initialize_markets(market_names)
            self.market_pair = ArbitrageMarketPair(
                *([self.markets[primary_market], raw_primary_symbol] +
                  list(primary_assets) +
                  [self.markets[secondary_market], raw_secondary_symbol] +
                  list(secondary_assets)))

            strategy_logging_options = ArbitrageStrategy.OPTION_LOG_ALL

            self.strategy = ArbitrageStrategy(
                market_pairs=[self.market_pair],
                min_profitability=min_profitability,
                logging_options=strategy_logging_options)

        else:
            raise NotImplementedError

        try:
            self.clock = Clock(ClockMode.REALTIME)
            if self.wallet is not None:
                self.clock.add_iterator(self.wallet)
            for market in self.markets.values():
                if market is not None:
                    self.clock.add_iterator(market)
            self.clock.add_iterator(self.strategy)
            self.strategy_task: asyncio.Task = asyncio.ensure_future(
                self.clock.run())
            self.app.log(
                f"\n'{strategy_name}' strategy started.\n"
                f"You can use the `status` command to query the progress.")
        except Exception as e:
            self.logger().error(str(e), exc_info=True)
Esempio n. 16
0
ddex_market.add_data(ddex_loader)

binance_market.set_quantization_param(QuantizationParams(
    "ETHUSDT", 5, 3, 5, 3))
ddex_market.set_quantization_param(QuantizationParams("WETH-DAI", 5, 3, 5, 3))

market_pair1 = ArbitrageMarketPair(*([ddex_market] + list(ddex_symbol) +
                                     [binance_market] + list(binance_symbol)))

strategy = ArbitrageStrategy(
    [market_pair1],
    0.025,
    logging_options=ArbitrageStrategy.OPTION_LOG_CREATE_ORDER)

clock = Clock(ClockMode.BACKTEST,
              start_time=start.timestamp(),
              end_time=end.timestamp())
clock.add_iterator(binance_market)
clock.add_iterator(ddex_market)
clock.add_iterator(strategy)

binance_market.set_balance("ETH", 100.0)
binance_market.set_balance("USDT", 10000.0)
ddex_market.set_balance("WETH", 100.0)
ddex_market.set_balance("DAI", 10000.0)

clock.backtest_til(start.timestamp() + 1)

ddex_weth_price = ddex_market.get_price("WETH-DAI", False)
binance_eth_price = binance_market.get_price("ETHUSDT", False)
start_ddex_portfolio_value = ddex_market.get_balance(
Esempio n. 17
0
import asyncio
import time

from hummingbot.cli.settings import get_erc20_token_addresses
from wings.web3_wallet import Web3Wallet
from wings.clock import Clock, ClockMode
from wings.ddex_market import DDEXMarket
from wings.ethereum_chain import EthereumChain
from wings.order_book_tracker import OrderBookTrackerDataSourceType

token_addresses = get_erc20_token_addresses(["WETH", "DAI"])
zrx_addr = "0x74622073a4821dbfd046E9AA2ccF691341A076e1"
pkey = "7BB21B1C4C9C0A474BCD08C1BA3C31ACEA8B6840AC72A67EDD38CB32899CBF87"
server = "http://aws-mainnet-1.mainnet-rpc-headless.mainnet:8545"
clock = Clock(ClockMode.REALTIME)
wallet = Web3Wallet(pkey, [server],
                    token_addresses,
                    chain=EthereumChain.MAIN_NET)
market = DDEXMarket(
    wallet,
    server,
    order_book_tracker_data_source_type=OrderBookTrackerDataSourceType.
    EXCHANGE_API,
    symbols=["WETH-DAI"])
clock.add_iterator(wallet)
clock.add_iterator(market)


async def main():
    begin = time.time() // 1
    async def start_market_making(self, strategy_name: str):
        strategy_cm = get_strategy_config_map(strategy_name)
        if strategy_name == "cross_exchange_market_making":
            maker_market = strategy_cm.get("maker_market").value.lower()
            taker_market = strategy_cm.get("taker_market").value.lower()
            raw_maker_symbol = strategy_cm.get(
                "maker_market_symbol").value.upper()
            raw_taker_symbol = strategy_cm.get(
                "taker_market_symbol").value.upper()
            min_profitability = strategy_cm.get("min_profitability").value
            trade_size_override = strategy_cm.get("trade_size_override").value
            strategy_report_interval = global_config_map.get(
                "strategy_report_interval").value
            limit_order_min_expiration = strategy_cm.get(
                "limit_order_min_expiration").value
            cancel_order_threshold = strategy_cm.get(
                "cancel_order_threshold").value
            active_order_canceling = strategy_cm.get(
                "active_order_canceling").value
            top_depth_tolerance_rules = [(re.compile(re_str), value)
                                         for re_str, value in strategy_cm.get(
                                             "top_depth_tolerance").value]
            top_depth_tolerance = 0.0

            for regex, tolerance_value in top_depth_tolerance_rules:
                if regex.match(raw_maker_symbol) is not None:
                    top_depth_tolerance = tolerance_value

            try:
                maker_assets: Tuple[str, str] = SymbolSplitter.split(
                    maker_market, raw_maker_symbol)
                taker_assets: Tuple[str, str] = SymbolSplitter.split(
                    taker_market, raw_taker_symbol)
            except ValueError as e:
                self.app.log(str(e))
                return

            market_names: List[Tuple[str, List[str]]] = [
                (maker_market, [raw_maker_symbol]),
                (taker_market, [raw_taker_symbol])
            ]
            self._initialize_wallet(
                token_symbols=list(set(maker_assets + taker_assets)))
            self._initialize_markets(market_names)
            self.assets = set(maker_assets + taker_assets)

            self.market_pair = CrossExchangeMarketPair(
                *([self.markets[maker_market], raw_maker_symbol] +
                  list(maker_assets) +
                  [self.markets[taker_market], raw_taker_symbol] +
                  list(taker_assets) + [top_depth_tolerance]))

            strategy_logging_options = (
                CrossExchangeMarketMakingStrategy.OPTION_LOG_CREATE_ORDER
                | CrossExchangeMarketMakingStrategy.OPTION_LOG_ADJUST_ORDER |
                CrossExchangeMarketMakingStrategy.OPTION_LOG_MAKER_ORDER_FILLED
                | CrossExchangeMarketMakingStrategy.OPTION_LOG_REMOVING_ORDER
                | CrossExchangeMarketMakingStrategy.OPTION_LOG_STATUS_REPORT |
                CrossExchangeMarketMakingStrategy.OPTION_LOG_MAKER_ORDER_HEDGED
            )

            self.strategy = CrossExchangeMarketMakingStrategy(
                market_pairs=[self.market_pair],
                min_profitability=min_profitability,
                status_report_interval=strategy_report_interval,
                logging_options=strategy_logging_options,
                trade_size_override=trade_size_override,
                limit_order_min_expiration=limit_order_min_expiration,
                cancel_order_threshold=cancel_order_threshold,
                active_order_canceling=active_order_canceling)

        elif strategy_name == "arbitrage":
            primary_market = strategy_cm.get("primary_market").value.lower()
            secondary_market = strategy_cm.get(
                "secondary_market").value.lower()
            raw_primary_symbol = strategy_cm.get(
                "primary_market_symbol").value.upper()
            raw_secondary_symbol = strategy_cm.get(
                "secondary_market_symbol").value.upper()
            min_profitability = strategy_cm.get("min_profitability").value
            try:
                primary_assets: Tuple[str, str] = SymbolSplitter.split(
                    primary_market, raw_primary_symbol)
                secondary_assets: Tuple[str, str] = SymbolSplitter.split(
                    secondary_market, raw_secondary_symbol)

            except ValueError as e:
                self.app.log(str(e))
                return

            market_names: List[Tuple[str, List[str]]] = [
                (primary_market, [raw_primary_symbol]),
                (secondary_market, [raw_secondary_symbol])
            ]
            self._initialize_wallet(
                token_symbols=list(set(primary_assets + secondary_assets)))
            self._initialize_markets(market_names)
            self.assets = set(primary_assets + secondary_assets)

            self.market_pair = ArbitrageMarketPair(
                *([self.markets[primary_market], raw_primary_symbol] +
                  list(primary_assets) +
                  [self.markets[secondary_market], raw_secondary_symbol] +
                  list(secondary_assets)))

            strategy_logging_options = ArbitrageStrategy.OPTION_LOG_ALL

            self.strategy = ArbitrageStrategy(
                market_pairs=[self.market_pair],
                min_profitability=min_profitability,
                logging_options=strategy_logging_options)
        elif strategy_name == "discovery":
            try:
                market_1 = strategy_cm.get("primary_market").value.lower()
                market_2 = strategy_cm.get("secondary_market").value.lower()
                target_symbol_1 = list(
                    strategy_cm.get("target_symbol_1").value)
                target_symbol_2 = list(
                    strategy_cm.get("target_symbol_2").value)
                target_profitability = float(
                    strategy_cm.get("target_profitability").value)
                target_amount = float(strategy_cm.get("target_amount").value)
                equivalent_token: List[List[str]] = list(
                    strategy_cm.get("equivalent_tokens").value)

                market_names: List[Tuple[str, List[str]]] = [
                    (market_1, target_symbol_1), (market_2, target_symbol_2)
                ]

                target_base_quote_1: List[Tuple[str, str]] = [
                    SymbolSplitter.split(market_1, symbol)
                    for symbol in target_symbol_1
                ]
                target_base_quote_2: List[Tuple[str, str]] = [
                    SymbolSplitter.split(market_2, symbol)
                    for symbol in target_symbol_2
                ]

                for asset_tuple in (target_base_quote_1 + target_base_quote_2):
                    self.assets.add(asset_tuple[0])
                    self.assets.add(asset_tuple[1])

                self._initialize_wallet(token_symbols=list(self.assets))
                self._initialize_markets(market_names)
                self.market_pair = DiscoveryMarketPair(*([
                    self.markets[market_1],
                    self.markets[market_1].get_active_exchange_markets
                ] + [
                    self.markets[market_2],
                    self.markets[market_2].get_active_exchange_markets
                ]))

                self.strategy = DiscoveryStrategy(
                    market_pairs=[self.market_pair],
                    target_symbols=target_base_quote_1 + target_base_quote_2,
                    equivalent_token=equivalent_token,
                    target_profitability=target_profitability,
                    target_amount=target_amount)
            except Exception as e:
                self.app.log(str(e))
                self.logger().error("Error initializing strategy.",
                                    exc_info=True)
        else:
            raise NotImplementedError

        try:
            self.clock = Clock(ClockMode.REALTIME)
            if self.wallet is not None:
                self.clock.add_iterator(self.wallet)
            for market in self.markets.values():
                if market is not None:
                    self.clock.add_iterator(market)
            self.clock.add_iterator(self.strategy)
            self.strategy_task: asyncio.Task = asyncio.ensure_future(
                self._run_clock())
            self.app.log(
                f"\n  '{strategy_name}' strategy started.\n"
                f"  You can use the `status` command to query the progress.")

            self.starting_balances = await self.wait_till_ready(
                self.balance_snapshot)
            self.stop_loss_tracker = StopLossTracker(
                self.data_feed, list(self.assets), list(self.markets.values()),
                lambda *args, **kwargs: asyncio.ensure_future(
                    self.stop(*args, **kwargs)))
            await self.wait_till_ready(self.stop_loss_tracker.start)
        except Exception as e:
            self.logger().error(str(e), exc_info=True)
 def setUp(self):
     self.clock: Clock = Clock(ClockMode.BACKTEST, start_time=self.start_time, end_time=self.end_time)
     self.order_book_loader: DDEXOrderBookLoader = DDEXOrderBookLoader("WETH-DAI", "WETH", "DAI")
     self.order_book: OrderBook = self.order_book_loader.order_book
     self.clock.add_iterator(self.order_book_loader)
Esempio n. 20
0
 def setUp(self):
     self.clock: Clock = Clock(ClockMode.BACKTEST, start_time=self.start_time, end_time=self.end_time)
     self.order_book_loader: RadarRelayOrderBookLoader = RadarRelayOrderBookLoader("WETH-DAI", "WETH", "DAI")
     self.order_book: RadarRelayOrderBook = self.order_book_loader.order_book
     self.active_order_tracker: RadarRelayActiveOrderTracker = self.order_book_loader.active_order_tracker
     self.clock.add_iterator(self.order_book_loader)