Пример #1
0
    def test_new_long_position_buy(self, portfolio, paperexchange, asset):
        quantity = 1.0
        price = 10000.0
        time = paperexchange.data_provider.get_time()
        print("START TIME = {}".format(time))
        buy_order = build_limit_buy_order(portfolio.balance, paperexchange,
                                          asset, quantity, price, time)
        updated_orders = process_orders(paperexchange, portfolio.balance,
                                        [buy_order])

        # Pre portfolio update:
        assert portfolio.cash == 20000
        assert portfolio.total_value == 20000

        latest_prices = {asset.symbol: 10000}
        print("updated_order trade time {}".format(
            updated_orders[0].trades[0].trade_time))
        portfolio.update(time, updated_orders, latest_prices)
        portfolio.update_performance(
            time, time + paperexchange.data_provider.feed.timeframe.delta)

        assert portfolio.cash == 10000
        assert portfolio.positions_value == 10000
        # cash + positions_value = total value
        assert portfolio.total_value == 20000
        assert portfolio.positions[0].cost_price == 10000
        assert portfolio.positions[0].market_value == 10000
        assert portfolio.perf.pnl == 0.0
Пример #2
0
    def test_order_manager(self, paperexchange, asset, balance):
        quantity = 1.0
        price = 10000.0
        start_time = paperexchange.data_provider.get_time()
        buy_order = om.build_limit_buy_order(balance, paperexchange, asset,
                                             quantity, price, start_time)

        assert balance.get(coins.USDT)[BalanceType.TOTAL] == 20000
        assert balance.get(coins.BTC)[BalanceType.TOTAL] == 0.0
        updated_orders = om.process_orders(paperexchange, balance, [buy_order])

        assert balance.get(coins.USDT)[BalanceType.TOTAL] == 20000
        assert balance.get(coins.USDT)[BalanceType.FREE] == 10000
        assert balance.get(coins.USDT)[BalanceType.USED] == 10000
        assert balance.get(coins.BTC)[BalanceType.TOTAL] == 0.0

        print("updated orders: ", updated_orders)
Пример #3
0
    def test_existing_long_position_buy(self, portfolio, paperexchange, asset):
        quantity = 1.0
        price = 9000
        time = paperexchange.data_provider.get_time()
        buy_order = build_limit_buy_order(portfolio.balance, paperexchange,
                                          asset, quantity, price, time)

        updated_orders = process_orders(paperexchange, portfolio.balance,
                                        [buy_order])

        latest_prices = {asset.symbol: 9000}
        portfolio.update(time, updated_orders, latest_prices)
        portfolio.update_performance(
            time, time + paperexchange.data_provider.feed.timeframe.delta)

        assert portfolio.cash == 1000
        assert portfolio.positions_value == 18000
        # cash + positions_value == total_value
        assert portfolio.total_value == 19000
        assert portfolio.positions[0].cost_price == 9500
        assert portfolio.positions[0].market_value == 18000
        assert portfolio.positions[0].cost_value == 19000
        # position.market_value - position.cost_value = pnl
        assert portfolio.perf.pnl == -1000  # price went down
Пример #4
0
def backtest(name, exchange, balance, portfolio, feed, strategy):
    '''
    :name = name of your current experiment run
    '''
    # Where we will save the record
    root = os.path.join(cfg.DATA_DIR, name)

    # This can be retrieved from the user's global config
    store = DATA_STORES[cfg.DATA_STORE](root=root)

    config = {
        'experiment': name,
        'strategy': strategy.name,
    }

    record = Record(
        config=config,
        portfolio=portfolio,
        balance=portfolio.balance,
        store=store
    )
    ctx = Context(
        exchange=exchange,
        feed=feed,
        record=record
    )

    row = feed.next()
    last_port_update_time = row.get('utc') - feed.timeframe.delta
    orders = []
    record.save()
    while row is not None:

        output = strategy.process(row, ctx)
        # Add any new orders from strategy output
        new_orders = output['new_orders']
        cancel_ids = output['cancel_ids']

        orders.extend(new_orders)
        # TODO: Cancelling orders
        # should we auto-cancel any outstanding orders
        # or should we leave this decision up to the Strategy?
        # How do we confirm the order has been cancelled by the exchange?
        # order_manager.cancel_orders(exchange, cancel_ids)

        updated_orders = order_manager.process_orders(
            exchange, portfolio.balance, orders)

        # Get the symbols traded in this strategy
        symbols_traded = get_symbols_traded(
                orders, portfolio.positions)

        # Update latest prices of positions
        latest_prices = get_latest_prices(
            symbols_traded, row, exchange.id)

        # Portfolio needs to know about new trades and latest prices
        portfolio.update(
            last_port_update_time, row.get('utc') , updated_orders, latest_prices)

        last_port_update_time = row.get('utc')

        # Update record with updates to orders
        for order in updated_orders:
            record.orders[order.id] = order

        # Reset open orders list to only track open/created orders
        orders = order_manager.get_open_orders(updated_orders)
        orders.extend(
            order_manager.get_created_orders(updated_orders))

        record.save()
        row = feed.next()

    return record
Пример #5
0
def live(name, exchange, balance, portfolio, feed, strategy):
    '''
    :name = name of your current experiment run
    '''
    print("LIVE TRADING! My, man!")

    # Where we will save the record
    root = os.path.join(cfg.DATA_DIR, name)

    # This can be retrieved from the user's global config
    store = DATA_STORES[cfg.DATA_STORE](root=root)

    config = {
        'experiment': name,
        'strategy': strategy.name,
    }
    record = Record(
        config=config,
        portfolio=portfolio,
        balance=portfolio.balance,
        store=store
    )
    ctx = Context(
        exchange=exchange,
        feed=feed,
        record=record
    )

    row = feed.next()
    last_port_update_time = datetime.utcnow()
    orders = []
    record.save()

    while True:

        if row is not None:
            output = strategy.process(row, ctx)
            # Add any new orders from strategy output
            new_orders = output['new_orders']
            cancel_ids = output['cancel_ids']

            # Add new orders to our orders list
            orders.extend(new_orders)


        # TODO: Cancelling orders
        # should we auto-cancel any outstanding orders
        # or should we leave this decision up to the Strategy?
        # order_manager.cancel_orders(exchange, cancel_ids)

        # Place new orders, retry failed orders, sync existing orders
        updated_orders = order_manager.process_orders(
                            exchange=exchange,
                            balance=portfolio.balance,
                            open_or_new_orders=orders
                        )
        # Get the symbols traded in this strategy
        symbols_traded = get_symbols_traded(
            orders, portfolio.positions)

        # Update latest prices of positions
        latest_prices = get_latest_prices(
                symbols_traded, row, exchange.id)

        current_time = datetime.utcnow()
        # Portfolio needs to know about new trades/latest prices
        portfolio.update(
            last_port_update_time, current_time, updated_orders, latest_prices)

        # Keep updating last time we updated our portfolio
        last_port_update_time = current_time

        # Reset open orders list to only track open/created orders
        orders = order_manager.get_open_orders(updated_orders)
        orders.extend(
            order_manager.get_created_orders(updated_orders))

        # Update record with updates to orders
        for order in updated_orders:
            record.orders[order.id] = order

        record.save()
        row = feed.next()

    return record