示例#1
0
    async def persistent_submit(self, side, price, qty, ioc, quote):
        tries = 0
        unsuccessful_submit = True

        p = price
        q = qty

        while (tries < 5 and unsuccessful_submit):
            try:
                await self._trader.submit_order(side=side,
                                                price=p,
                                                qty=q,
                                                ioc=ioc,
                                                quote=quote)
                unsuccessful_submit = False
            except PostOnlyException:
                previous_price = p
                previous_qty = q

                if side == Side.BID:
                    p = previous_price - make_price(0.01)
                    q = make_qty(
                        Decimal(round((previous_qty * previous_price) / p, 8)))
                else:
                    p = previous_price + make_price(0.01)
                    q = make_qty(
                        Decimal(round((previous_qty * previous_price) / p, 8)))
                tries += 1

        if unsuccessful_submit:
            log.warning('Tried to place order 5x. Giving up...')
示例#2
0
    async def on_signal(self, action, update):
        strp_time = update['timestamp'].split('.')[0].split('+')[0]
        curr_time = time.mktime(
            dt.datetime.strptime(strp_time, '%Y-%m-%d %H:%M:%S').timetuple())

        book = update['book']
        if action == 'BUY':
            if self._pnl_manager.get_cash_value() <= Decimal(1.00):
                return

            price = make_price(book['asks'][0]['price'])
            cash = self._pnl_manager.get_cash_value()
            qty = cash / price

            await self._trader.submit_order(side=Side.BID,
                                            price=price,
                                            qty=make_qty(Decimal(qty)),
                                            ioc=True,
                                            quote=True)
            self._last_buy_ts = curr_time
        else:
            if self._pnl_manager.get_crypto_value(book) <= Decimal(0.01):
                return

            price = make_price(book['bids'][0]['price'])
            qty = self._pnl_manager.crypto_coins

            await self._trader.submit_order(side=Side.ASK,
                                            price=price,
                                            qty=make_qty(Decimal(qty)),
                                            ioc=True,
                                            quote=True)
            self._last_sell_ts = curr_time
示例#3
0
def main(args):
    params = {
        'api_url': gdax.OrderEntryGateway.SANDBOX_URL,
        'api_key': args['<API_KEY>'],
        'api_secret': args['<API_SECRET>'],
        'passphrase': args['<PASSPHRASE>'],
        'ip': args['<IP>'],
        'port': args['<PORT>'],
        'sandbox': False if (args['<SANDBOX>'] == "False") else True,
        'instrument': args['<INSTRUMENT>']
    }

    log.info('Starting Anchor Strategy for {} in {} mode',
             params['instrument'],
             'SANDBOX' if params['sandbox'] else 'PRODUCTION')

    # TODO: Set up limits through configuration
    StrategyConfig['limits'] = {}
    StrategyConfig['limits']['max_order_qty'] = make_qty('2')
    StrategyConfig['limits']['max_order_value'] = make_price('1000')
    StrategyConfig['limits']['max_open_value'] = 1000

    loop = asyncio.get_event_loop()
    anchor_strategy = Anchor(loop)
    loop.run_until_complete(anchor_strategy.run(params))
示例#4
0
    async def socket_handler(self, request):
        resp = aiohttp.web.WebSocketResponse()
        ok, protocol = resp.can_prepare(request)
        if not ok:
            return aiohttp.web.Response(text='Somthing went wrong')

        await resp.prepare(request)

        try:
            request.app['sockets'].append(resp)
            async for msg in resp:
                if msg.type == aiohttp.web.WSMsgType.TEXT:
                    req = json.loads(msg.data)
                    if 'submit' in req:
                        logging.info('Recieved request: {}'.format(req))
                        if is_valid_submit(req['submit']):
                            submit = req['submit']
                            side = Side.BUY \
                                if submit['side'] == 'BUY' else Side.SELL

                            submit = await self.trader.submit_order(
                                side=side,
                                price=make_price(submit['price']),
                                qty=make_qty(submit['qty']),
                                ioc=submit['ioc'],
                                quote=submit['quote'])
                        else:
                            self.broadcast(
                                'submit_nack', {
                                    'trigger': {
                                        'msg': 'submit',
                                        'args': req
                                    },
                                    'error': 'One+ fields are invalid!'
                                })
                    elif 'cancel_session' in req:
                        await self.trader.cancel_session()
                    elif 'cancel_all' in req:
                        await self.trader.cancel_all()
                    elif 'admin' in req:
                        if req['admin'] == 'GetBalance':
                            msg = await self.get_balance_msg()
                            resp.send_str(json.dumps(msg))
                        elif req['admin'] == 'ListOrders':
                            await self.trader.broadcast_orders()
                        elif req['admin'] == 'GetFills':
                            msg = await self.get_fills_msg()
                            resp.send_str(json.dumps(msg))
                else:
                    pass
        except Exception as e:
            self.broadcast('UnexpectedError', e)
            logging.error('Unexpected Error: {}'.format(e))
        finally:
            try:
                request.app['sockets'].remove(resp)
            except ValueError:
                pass

            return resp
示例#5
0
 def __init__(self, gateway, instrument):
     limits = LimitChecker(max_order_qty=make_qty('0.8'),
                           max_order_value=make_price('200.50'),
                           max_open_value=200)
     self.session = Session(gateway=gateway,
                            instrument=instrument,
                            limits=limits)
     self.session.add_event_handler(self)
示例#6
0
    async def on_signal(self, action, update):
        if not self._enabled:
            return

        await self._trader.cancel_all()

        at_min_spread = self._at_min_spread()

        book = update['book']
        if action == 'BUY':
            if self._pnl_manager.get_cash_value() <= Decimal(1.00):
                return

            cash = Decimal(self._pnl_manager.get_cash_value())

            if at_min_spread:
                price = make_price(float(book['asks'][0]['price']))
                qty = Decimal(round(cash / price, 8))
            else:
                price = make_price(float(book['asks'][0]['price']) - 0.01)
                qty = Decimal(round(cash / price, 8))

            await self._jarvis.persistent_submit(side=Side.BID,
                                                 price=price,
                                                 qty=make_qty(qty),
                                                 ioc=False,
                                                 quote=True)
        else:
            if self._pnl_manager.get_crypto_value(book) <= Decimal(0.01):
                return

            qty = Decimal(round(self._pnl_manager.crypto_coins, 8))
            if at_min_spread:
                price = make_price(float(book['bids'][0]['price']))
            else:
                price = make_price(float(book['bids'][0]['price']) + 0.01)

            await self._jarvis.persistent_submit(side=Side.ASK,
                                                 price=price,
                                                 qty=make_qty(Decimal(qty)),
                                                 ioc=False,
                                                 quote=True)

        # Notify dashboard listeners
        await self._broadcast_state("Flipped Signal")
示例#7
0
 def __init__(self, gateway, instrument):
     limits = LimitChecker(max_order_qty=make_qty('100'),
                           max_order_value=make_price('20000'),
                           max_open_value=20000)
     self.session = Session(gateway=gateway,
                            instrument=instrument,
                            limits=limits)
     self.session.add_event_handler(self)
     self.orders = []
     self._broadcast_cb = None
示例#8
0
    def on_resting_trade(self, price, qty, side):
        # log.info("resting trade: {} {} {}".format(price, qty, side))
        order = Order(None, None, side, make_price(price), qty, 0, qty)

        # pretend it is like an on cancel
        if side is Side.BID:
            self._handler.update_reserves(price * qty, 0)
        else:
            self._handler.update_reserves(0, qty)

        if self._handler is not None:
            self._handler.on_fill(order, qty)
示例#9
0
    async def run(self):
        await self.session.wait_ready()
        order = await self.submit_order(side=Side.BUY,
                                        price=make_price(300),
                                        qty=make_qty('0.50'))
        log.info('Submitted: order={}', order)

        await asyncio.sleep(3)

        ioc = await self.submit_ioc(side=Side.BUY,
                                    price=make_price(1000),
                                    qty=make_qty('0.02'))
        log.info('Submitted IOC: order={}', ioc)

        await asyncio.sleep(3)

        try:
            if order is not None:
                await order.cancel()
        except oe_exceptions.CancelNack as cnack:
            log.error('{}: {}', cnack.order, cnack)

        await self.check_balance()
示例#10
0
def main(args):
    loop = asyncio.get_event_loop()
    strategy_harness = StrategyHarness(loop)

    params = {
        'api_url': gdax.OrderEntryGateway.SANDBOX_URL,
        'api_key': args['<API_KEY>'],
        'api_secret': args['<API_SECRET>'],
        'passphrase': args['<PASSPHRASE>'],
        'ip': args['<IP>'],
        'port': args['<PORT>'],
        'sandbox': False if (args['<SANDBOX>'] == "False") else True,
        'instrument': args['<INSTRUMENT>']
    }

    log.info('Starting Aesop Strategy for {} in {} mode', params['instrument'],
             'SANDBOX' if params['sandbox'] else 'PRODUCTION')

    # TODO: Set up limits through configuration
    StrategyConfig['limits'] = {}
    StrategyConfig['limits']['max_order_qty'] = make_qty('3')
    StrategyConfig['limits']['max_order_value'] = make_price('1000')
    StrategyConfig['limits']['max_open_value'] = 1000

    try:
        loop.run_until_complete(strategy_harness.run(params))
    except KeyboardInterrupt:
        log.info('Keyboard Interrupt - Shutting down Aesop Strategy')

        # Cancel all running tasks
        for t in asyncio.Task.all_tasks():
            t.cancel()

        loop.run_forever()  # Wait for tasks to finish cleanup.

        # Gather exceptions.
        for t in asyncio.Task.all_tasks():
            try:
                t.exception()
            except Exception:
                log.exception('Exception during shutdown: {}', t)
    finally:
        loop.close()
示例#11
0
 def _slacked_price(self, price):
     return round(make_price(price), 2)
示例#12
0
 def __init__(self, instrument):
     self._instrument = instrument
     self.open_long = make_qty(0)
     self.open_short = make_qty(0)
     self.base_amount = make_qty(0)
     self.quote_amount = make_price(0)
示例#13
0
 def __init__(self, level_side):
     self._price = make_price(level_side['price'])
     self._qty = make_qty(level_side['qty'])