Exemplo n.º 1
0
def main(event, context):
    try:
        _tickers = event.get("tickers")
        _position_size = event.get("position-size")
        _strategy = event.get("strategy")
        account_alias = event.get("account-alias")

        kms = Kms()
        session = get_session()

        if environ.get("STAGE") == "test":
            wait_for_db_init(session)

        candle_repository = CandleRepository(session)
        account_repository = AccountRepository(session, kms)
        order_repository = OrderRepository(session)

        accounts = account_repository.get_all_active_upbit_accounts(alias=account_alias)
        db_feed = DbFeed(exchange=UpbitExchange.build(accounts[0]), candle_repository=candle_repository)

        tickers = _tickers or get_trading_tickers()
        strategy = get_strategy_by_name(name=_strategy)

        feeds_by_ticker = db_feed.build_feeds_by_ticker(tickers=tickers)
        strategies_by_ticker = get_trading_strategies_by_ticker(tickers=tickers, override_strategy=strategy)

        logger.info(f"accounts = {accounts}")
        orders = []

        for account in accounts:
            send_credential_expiry_reminder(account)

            exchange = UpbitExchange.build(account)
            asset_manager = AssetManager(exchange)
            trader = Trader(asset_manager, exchange, session, account, order_repository)

            for ticker, strategies in strategies_by_ticker.items():
                for strategy in strategies:
                    logger.info(f"trading with strategy = {strategy}, ticker = {ticker}")

                    wait_order = trader.trade(ticker=ticker, strategy=strategy(feeds_by_ticker[ticker]), position_size=_position_size)

                    if wait_order is not None:
                        orders.append(wait_order)

        return {
            "statusCode": 200,
            "body": ",".join([order.get_id() for order in orders])
        }
    except Exception as e:
        stack = traceback.format_exc()
        logger.error(e)

        return {
            "statusCode": 500,
            "body": stack
        }
Exemplo n.º 2
0
def update_credential(id: int, access_key: str, secret_key: str, expired_at: str):
    session = get_session()
    kms = Kms()
    account_repository = AccountRepository(session, kms)

    account_repository.update_credential(
        id=id,
        access_key=access_key,
        secret_key=secret_key,
        expired_at=datetime.fromisoformat(expired_at)
    )
Exemplo n.º 3
0
def add(vendor: str, access_key: str, secret_key: str, expired_at: str, alias: str):
    session = get_session()
    kms = Kms()
    account_repository = AccountRepository(session, kms)

    account_repository.add_account(
        vendor=vendor,
        access_key=access_key,
        secret_key=secret_key,
        expired_at=datetime.fromisoformat(expired_at),
        alias=alias
    )
Exemplo n.º 4
0
 def post():
     """Create a new page"""
     session = get_session()
     page = Page()
     session.add(page)
     session.flush()
     change = Change(page_id=page.oid,
                     title=request.args['title'],
                     text=request.args['text'])
     session.add(change)
     session.commit()
     return {'page_id': page.oid}, 201
Exemplo n.º 5
0
 def put(page_id):
     """Update the page"""
     session = get_session()
     page = session.query(Page).get(page_id)
     if page is None:
         return 'Page not found', 404
     change = Change(page_id=page.oid,
                     title=request.args['title'],
                     text=request.args['text'])
     session.add(change)
     session.flush()
     session.commit()
     return {'change_id': change.oid}, 200
Exemplo n.º 6
0
def main(event, context):
    try:
        account_alias = event.get("account-alias")

        kms = Kms()
        session = get_session()

        if environ.get("STAGE") == "test":
            wait_for_db_init(session)

        order_repository = OrderRepository(session)
        account_repository = AccountRepository(session, kms)

        accounts = account_repository.get_all_active_upbit_accounts(
            alias=account_alias)

        logger.info(f"accounts = {accounts}")

        filled_order_ids = []

        for account in accounts:
            exchange = UpbitExchange.build(account)

            open_orders = order_repository.get_open_orders(
                account_id=account.get_id(), count=20)

            logger.info(
                f"alias = {account.get_alias()}, syncing open orders = {open_orders}"
            )

            for open_order in open_orders:
                order_data = exchange.get_order(order_id=open_order.get_id())

                if not order_data or not order_data.is_filled():
                    continue

                logger.info(f"updating order data = {order_data}")

                order_repository.finish_order(id=open_order.get_id(),
                                              order=order_data)
                filled_order_ids.append(open_order.get_id())

        return {
            "statusCode": 200,
            "body": ",".join([order_id for order_id in filled_order_ids])
        }
    except Exception as e:
        stack = traceback.format_exc()
        logger.error(e)

        return {"statusCode": 500, "body": stack}
Exemplo n.º 7
0
def main(event, context) -> LambdaResponse:
    try:
        _tickers = event.get("tickers")
        _start = event.get("start")
        _end = event.get("end")

        kms = Kms()
        session = get_session()

        if environ.get("STAGE") == "test":
            wait_for_db_init(session)

        account_repository = AccountRepository(session, kms)
        candle_repository = CandleRepository(session)

        account = account_repository.get_active_account()

        if account is None:
            raise ValueError(f"active account doesn't exists")

        exchange = UpbitExchange.build(account)

        tickers = _tickers or get_trading_tickers()

        today = date.today()
        tomorrow = today + datetime.timedelta(days=1)

        start = _start if _start is not None else today.strftime("%Y-%m-%d")
        end = _end if _end is not None else tomorrow.strftime("%Y-%m-%d")

        candles: List[Candle] = []

        for ticker in tickers:
            for candle_info in exchange.get_day_candles(ticker, start, end):
                candles.append(candle_info)

        candle_repository.add_candles(candles)

        return {
            "statusCode": 200,
            "body": len(candles)
        }
    except Exception as e:
        stack = traceback.format_exc()
        logger.error(e)

        return {
            "statusCode": 500,
            "body": stack
        }
Exemplo n.º 8
0
    def get(page_id=None):
        """Get the page or pages id"""
        session = get_session()
        if page_id is None:
            page_ids = [page.oid for page in session.query(Page)]
            return {'page_ids': page_ids}

        page = session.query(Page).get(page_id)
        if page is None:
            return 'Page not found', 404

        change = session.query(Page, Change).\
                         filter(Change.page_id == page.oid).\
                         order_by(Change.oid.desc()).\
                         first()[1]
        return {
            'change_id': change.oid,
            'title': change.title,
            'text': change.text
        }