Example #1
0
 def fetch_order(self, order_id):
     order = Dotdict({'status': 'closed', 'id': order_id})
     try:
         order = Dotdict(self.exchange.fetch_open_orders())
     except ccxt.OrderNotFound as e:
         self.logger.exception(type(e).__name__ + ": {0}".format(e))
     return order
Example #2
0
 def fetch_position_ws(self):
     pos = Dotdict(self.ws.position())
     pos.unrealisedPnlPcnt100 = pos.unrealisedPnlPcnt * 100
     self.logger.info(
         "POSITION: qty {currentQty} cost {avgCostPrice} pnl {unrealisedPnl}({unrealisedPnlPcnt100:.2f}%) {realisedPnl}"
         .format(**pos))
     return pos
Example #3
0
 def fetch_order_ws(self, order_id):
     orders = self.ws.all_orders()
     for o in orders:
         if o['id'] == order_id:
             order = Dotdict(self.exchange.parse_order(o))
             order.info = Dotdict(order.info)
             return order
     return Dotdict({'status': 'closed', 'id': order_id})
Example #4
0
 def fetch_balance(self):
     """資産情報取得"""
     balance = Dotdict(self.exchange.fetch_balance())
     balance.BTC = Dotdict(balance.BTC)
     self.logger.info(
         "BALANCE: free {free:.3f} used {used:.3f} total {total:.3f}".
         format(**balance.BTC))
     return balance
Example #5
0
 def fetch_balance_ws(self):
     balance = Dotdict(self.ws.funds())
     balance.BTC = Dotdict()
     balance.BTC.free = balance.availableMargin * 0.00000001
     balance.BTC.total = balance.marginBalance * 0.00000001
     balance.BTC.used = balance.BTC.total - balance.BTC.free
     self.logger.info(
         "BALANCE: free {free:.3f} used {used:.3f} total {total:.3f}".
         format(**balance.BTC))
     return balance
Example #6
0
 def fetch_ticker_ws(self):
     trade = self.__safe_api_recent_trades_ws()[-1]
     ticker = Dotdict(self.ws.get_ticker())
     ticker.datetime = pd.to_datetime(trade['timestamp'])
     self.logger.info(
         "TICK: bid {bid} ask {ask} last {last}".format(**ticker))
     self.logger.info(
         "TRD: price {price} size {size} side {side} tick {tickDirection} ".
         format(**(trade['info'])))
     return ticker, trade
Example #7
0
def args_parser(lst):
    """
    :param list(String): contains args ex) TEST_MODE=True
    :return: Dotdict
    """
    result = Dotdict()
    for e in lst:
        if "=" not in e:
            print(
                "The arguments should be obeyed with the map format such as TEST_MODE=True, but was "
                + e)
            continue
        key, value = e.split("=")
        result.update({key: value})
    return result
Example #8
0
    def bizlogic(self, ohlcv, ticker, position, balance, execution, strategy,
                 **other):
        pos = Dotdict(position)
        strategy.logger.debug("Execution:" + str(execution))
        # strategy.logger.debug("Position:" + str(pos))

        # strategy.logger.debug("Status: %s %s %s" % (self.followLogic.is_following,
        #                                       self.followLogic.last_orderid is not None,
        #                                       strategy.exchange.om.is_active(self.followLogic.last_orderid)))
        if self.followLogic.is_following \
                and self.followLogic.last_orderid is not None \
                and strategy.exchange.om.is_active(self.followLogic.last_orderid):
            self.followLogic.close_order(ticker)
        elif pos.openOrderBuyQty == 0 and pos.openOrderSellQty == 0:
            self.testLogic.create_orders(ticker)
        elif pos.openOrderBuyQty > pos.openOrderSellQty:
            leave_qty = pos.openOrderBuyQty - pos.openOrderSellQty
            self.testLogic.executed(ticker, 'sell', leave_qty)
        elif pos.openOrderSellQty > pos.openOrderBuyQty:
            leave_qty = pos.openOrderSellQty - pos.openOrderBuyQty
            self.testLogic.executed(ticker, 'buy', leave_qty)
        if self.testLogic.last_my_test_orders.ask != ticker.ask - SPREAD \
                and self.testLogic.last_my_test_orders.asksize != ticker.asksize \
                and not self.followLogic.is_following:
            self.testLogic.amend_orders(ticker, 'sell')
        if self.testLogic.last_my_test_orders.bid != ticker.bid + SPREAD \
                and self.testLogic.last_my_test_orders.bidsize != ticker.bidsize \
                and not self.followLogic.is_following:
            self.testLogic.amend_orders(ticker, 'buy')
Example #9
0
 def fetch_order(self, order_id):
     order = Dotdict({'status': 'closed', 'id': order_id})
     try:
         order = Dotdict(self.exchange.fetch_order(order_id))
         order.info = Dotdict(order.info)
     except ccxt.OrderNotFound as e:
         self.logger.warning(type(e).__name__ + ": {0}".format(e))
     return order
Example #10
0
 def fetch_ticker(self, symbol=None, timeframe=None):
     symbol = symbol or self.settings.symbol
     timeframe = timeframe or self.settings.timeframe
     book = self.exchange.fetch_order_book(symbol, limit=10)
     trade = self.__safe_api_recent_trades(symbol,
                                           limit=1,
                                           params={"reverse": True})
     ticker = Dotdict()
     ticker.bid, ticker.bidsize = book['bids'][0]
     ticker.ask, ticker.asksize = book['asks'][0]
     ticker.bids = book['bids']
     ticker.asks = book['asks']
     ticker.last = trade[0]['price']
     ticker.datetime = pd.to_datetime(trade[0]['datetime'])
     self.logger.info(
         "TICK: bid {bid} ask {ask} last {last}".format(**ticker))
     self.logger.info(
         "TRD: price {price} size {size} side {side} tick {tickDirection} ".
         format(**(trade[0]['info'])))
     return ticker, trade
Example #11
0
class SampleStrategy(StrategyBase):
    spread = 200
    qty = None
    last_my_order = Dotdict({"ask": None, "bid": None})
    last_ticker = Dotdict({"ask": None, "bid": None})

    def use(self, strategy):
        pass

    def bizlogic(self, ohlcv, ticker, position, balance, execution, strategy,
                 **other):
        pos = Dotdict(position)
        strategy.logger.debug("Execution:" + str(execution))
        # strategy.logger.debug("Position:" + str(pos))

        if pos.openOrderBuyQty == 0 and pos.openOrderSellQty == 0:
            strategy.logger.debug(
                "New Buy %s and New Sell %s" %
                (ticker.bid + self.spread, ticker.ask - self.spread))
            strategy.entry('B',
                           'buy',
                           QUANTITY,
                           limit=ticker.bid + self.spread)
            strategy.entry('S',
                           'sell',
                           QUANTITY,
                           limit=ticker.ask - self.spread)
            self.last_my_order.ask = ticker.ask - self.spread
            self.last_my_order.bid = ticker.bid + self.spread
            self.qty = QUANTITY
        elif pos.openOrderBuyQty > pos.openOrderSellQty > 0:  # MEMO: hedge order should be shadow
            leave_qty = pos.openOrderBuyQty - pos.openOrderSellQty
            strategy.logger.debug(
                "Partially Executed Sell %s then Others cancel and Decrease BuyVolume"
                % leave_qty)
            strategy.cancel('S')
            strategy.edit_order('B', 'buy', leave_qty)
            self.qty = leave_qty
        elif pos.openOrderSellQty > pos.openOrderBuyQty > 0:  # MEMO: hedge order should be shadow
            leave_qty = pos.openOrderSellQty - pos.openOrderBuyQty
            strategy.logger.debug(
                "Partially Executed Buy %s then Others cancel and Decrease SellVolume"
                % leave_qty)
            strategy.cancel('B')
            strategy.edit_order('S', 'sell', leave_qty)
            self.qty = leave_qty
        elif pos.openOrderBuyQty > pos.openOrderSellQty == 0:  # MEMO: hedge order should be shadow
            strategy.logger.debug("Fully Executed Sell then Amend Buy %s" %
                                  min(self.last_my_order.bid, ticker.ask))
            # strategy.logger.info(self.last_ticker.bids)
            if self.last_ticker.bid != ticker.bid:
                strategy.edit_order('B',
                                    'buy',
                                    self.qty,
                                    limit=min(ticker.bid + self.spread,
                                              ticker.ask))
                self.last_my_order.bid = min(ticker.bid + self.spread,
                                             ticker.ask)
            # elif self.last_ticker.bids[1][0] != ticker.bids[1][0]:  # MEMO: except self order
            #     strategy.edit_order('B', 'buy', self.qty, limit=min(ticker.bids[1][0] + self.spread, self.last_my_order.ask, ticker.ask))
            #     self.last_my_order.bid = min(ticker.bids[1][0] + self.spread, ticker.ask)
            else:
                pass
        elif pos.openOrderSellQty > pos.openOrderBuyQty == 0:  # MEMO: hedge order should be shadow
            strategy.logger.debug("Fully Executed Buy then Amend Sell %s" %
                                  max(self.last_my_order.ask, ticker.bid))
            # strategy.logger.info(self.last_ticker.asks)
            if self.last_ticker.ask != ticker.ask:
                strategy.edit_order('S',
                                    'sell',
                                    self.qty,
                                    limit=max(ticker.ask - self.spread,
                                              ticker.bid))
                self.last_my_order.ask = max(ticker.ask - self.spread,
                                             ticker.bid)
            # elif self.last_ticker.asks[1][0] != ticker.bids[1][0]:
            #     strategy.edit_order('S', 'sell', self.qty, limit=max(ticker.asks[1][0] - self.spread, self.last_my_order.bid, ticker.bid))
            #     self.last_my_order.bid = min(ticker.asks[1][0] - self.spread, ticker.bid)
            else:
                pass
        elif self.last_my_order.ask > ticker.ask:
            strategy.logger.debug("Amend Sell %s" % max(
                ticker.ask - self.spread, ticker.bid, self.last_my_order.ask))
            strategy.edit_order('S',
                                'sell',
                                self.qty,
                                limit=max(ticker.ask - self.spread, ticker.bid,
                                          self.last_my_order.ask))
            self.last_my_order.ask = max(ticker.ask - self.spread, ticker.bid,
                                         self.last_my_order.ask)
        elif self.last_my_order.bid < ticker.bid:
            strategy.logger.debug("Amend Buy %s" % min(
                ticker.bid + self.spread, ticker.ask, self.last_my_order.bid))
            strategy.edit_order('B',
                                'buy',
                                self.qty,
                                limit=min(ticker.bid + self.spread, ticker.ask,
                                          self.last_my_order.bid))
            self.last_my_order.bid = min(ticker.bid + self.spread, ticker.ask,
                                         self.last_my_order.bid)
        else:
            pass
        self.last_ticker = ticker
Example #12
0
    def create_order(self, myid, symbol, type, side, qty, price, params):
        self.logger.info(
            "Requesting to create a new order. symbol:%s, type:%s, side:%s, qty:%s, price:%s"
            % (symbol, type, side, qty, price))
        try:
            result = Right(
                self.exchange.create_order(symbol,
                                           type,
                                           side,
                                           qty,
                                           price=price,
                                           params=params))

            order = Dotdict()
            order.myid = myid
            order.accepted_at = datetime.utcnow().strftime(DATETIME_FORMAT)
            order.id = result.value['info']['id']
            order.status = 'accepted'
            order.symbol = symbol
            order.type = type.lower()
            order.side = side
            order.price = price if price is not None else 0
            order.average_price = 0
            order.cost = 0
            order.amount = qty
            order.filled = 0
            order.remaining = 0
            order.fee = 0
            self.om.add_order(order)
        except ccxt.BadRequest as e:
            self.logger.warning("Returned BadRequest: %s" % str(e))
            result = Left("Returned BadRequest: %s" % str(e))
        except Exception as e:
            self.logger.warning("Returned Exception: %s" % str(e))
            result = Left(str(e))
        return result.value
Example #13
0
class TestLogic:
    strategy = None
    last_my_test_orders = Dotdict({"ask": None, "bid": None})

    def __init__(self, strategy, followLogic):
        self.strategy = strategy
        self.followLogic = followLogic

    # MEMO: create new both orders
    def create_orders(self, ticker):
        if self.followLogic.is_following:
            self.followLogic.last_orderid = None
            self.strategy.logger.info("FOLLOWING MODE IS STOPPED")
        self.followLogic.is_following = False
        _ask = ticker.ask - SPREAD
        _bid = ticker.bid + SPREAD
        strategy.logger.debug("New Buy %s and New Sell %s" % (_ask, _bid))
        strategy.entry('B', 'buy', TEST_QUANTITY, limit=_bid)
        strategy.entry('S', 'sell', TEST_QUANTITY, limit=_ask)
        self.last_my_test_orders.ask = _ask
        self.last_my_test_orders.bid = _bid
        self.last_my_test_orders.asksize = TEST_QUANTITY
        self.last_my_test_orders.bidsize = TEST_QUANTITY

    def amend_orders(self, ticker, side):
        if side == 'sell':
            if ticker.ask == self.last_my_test_orders.ask:
                amend_price = max(ticker.ask - SPREAD, ticker.bid)
            else:
                amend_price = max(ticker.asks[1][0] - SPREAD, ticker.bid)
            strategy.logger.debug("Amend Sell %s" % amend_price)
            strategy.edit_order('S', 'sell', TEST_QUANTITY, limit=amend_price)
            self.last_my_test_orders.ask = amend_price
            self.last_my_test_orders.asksize = TEST_QUANTITY
        elif side == 'buy':
            if ticker.bid == self.last_my_test_orders.bid:
                amend_price = min(ticker.bid + SPREAD, ticker.ask)
            else:
                amend_price = min(ticker.bids[1][0] + SPREAD, ticker.ask)
            strategy.logger.debug("Amend Buy %s" % amend_price)
            strategy.edit_order('B', 'buy', TEST_QUANTITY, limit=amend_price)
            self.last_my_test_orders.bid = amend_price
            self.last_my_test_orders.bidsize = TEST_QUANTITY
        else:
            pass

    def executed(self, ticker, executed_side, executed_qty):
        if executed_side == 'sell':
            strategy.logger.debug(
                "Executed Sell %s then Others cancel and Decrease BuyVolume" %
                executed_qty)
            if executed_qty == TEST_QUANTITY:
                strategy.cancel('S')
            strategy.cancel('B')
            self.followLogic.follow('buy', ticker.ask, executed_qty,
                                    ticker.bid)
        elif executed_side == 'buy':
            strategy.logger.debug(
                "Executed Buy %s then Others cancel and Decrease SellVolume" %
                executed_qty)
            strategy.cancel('S')
            if executed_qty == TEST_QUANTITY:
                strategy.cancel('B')
            self.followLogic.follow('sell', ticker.bid, executed_qty,
                                    ticker.ask)
        else:
            pass
Example #14
0
 def fetch_position(self, symbol=None):
     """現在のポジションを取得"""
     symbol = symbol or self.settings.symbol
     res = self.exchange.privateGetPosition()
     pos = [
         x for x in res if x['symbol'] == self.exchange.market(symbol)['id']
     ]
     if len(pos):
         pos = Dotdict(pos[0])
         pos.timestamp = pd.to_datetime(pos.timestamp)
     else:
         pos = Dotdict()
         pos.currentQty = 0
         pos.avgCostPrice = 0
         pos.unrealisedPnl = 0
         pos.unrealisedPnlPcnt = 0
         pos.realisedPnl = 0
     pos.unrealisedPnlPcnt100 = pos.unrealisedPnlPcnt * 100
     self.logger.info(
         "POSITION: qty {currentQty} cost {avgCostPrice} pnl {unrealisedPnl}({unrealisedPnlPcnt100:.2f}%) {realisedPnl}"
         .format(**pos))
     return pos