Ejemplo n.º 1
0
def config_test():
    sql = "select * from entry"
    repository.read_sql(database=DATABASE, sql=sql)

    api = pybitflyer.API(api_key=Bitflyer.Api.value.KEY.value,
                         api_secret=Bitflyer.Api.value.SECRET.value)
    balance = api.getbalance()
    if "error_message" in balance:
        raise ConfigException()
Ejemplo n.º 2
0
def initialize():
    sql = "select * from ticker"
    ticker = repository.read_sql(database=database, sql=sql)
    if ticker.empty:
        message.info("initialize ticker")
        sql = "insert into ticker values (now(),0,0)"
        repository.execute(database=database, sql=sql, write=False)
Ejemplo n.º 3
0
 def __ticker(self):
     while True:
         try:
             sql = "select * from ticker"
             ticker = repository.read_sql(database=self.DATABASE, sql=sql)
             if not ticker.empty:
                 best_ask = ticker.at[0, "best_ask"]
                 best_bid = ticker.at[0, "best_bid"]
                 return {"best_ask": best_ask, "best_bid": best_bid}
         except Exception:
             message.error(traceback.format_exc())
Ejemplo n.º 4
0
    def get_historical_price(self, limit):
        sql = """
                select
                    cast(Time as datetime) as Date,
                    Open,
                    High,
                    Low,
                    Close
                from
                    (
                        select
                            date_format(
                                cast(op.date as datetime),
                                '%Y-%m-%d %H:%i:00'
                            ) as Time,
                            op.price as Open,
                            ba.High as High,
                            ba.Low as Low,
                            cl.price as Close
                        from
                            (
                                select
                                    max(price) as High,
                                    min(price) as Low,
                                    min(id) as open_id,
                                    max(id) as close_id
                                from
                                    execution_history
                                group by
                                    year(date),
                                    month(date),
                                    day(date),
                                    hour(date),
                                    minute(date)
                                order by
                                    max(date) desc
                                limit
                                    {limit}
                            ) ba
                            inner join execution_history op on op.id = ba.open_id
                            inner join execution_history cl on cl.id = ba.close_id
                    ) as ohlc
                order by
                    Time
            """.format(limit=limit)

        historical_price = repository.read_sql(database=self.DATABASE, sql=sql)
        first_Date = historical_price.loc[0]["Date"]
        sql = "delete from execution_history where date < '{first_Date}'"\
            .format(first_Date=first_Date)
        repository.execute(database=self.DATABASE, sql=sql, write=False)
        return historical_price
Ejemplo n.º 5
0
 def __has_changed_side(self, side):
     try:
         sql = "select * from entry"
         entry = \
             repository.read_sql(database=self.DATABASE, sql=sql)
         if entry.empty:
             message.warning("entry empty")
             return True
         latest_side = entry.at[0, "side"]
         if latest_side != side:
             message.warning("change side from", side, "to", latest_side)
             return True
         else:
             return False
     except Exception:
         message.error(traceback.format_exc())
Ejemplo n.º 6
0
import matplotlib.pyplot as plt

from lib import math, repository

asset = 1000000

sql = """
        select
            *
        from
            backtest_entry
        order by
            date
        """
be = repository.read_sql(database="tradingbot", sql=sql)

start_time = be.loc[0]["date"]
finish_time = be.loc[len(be) - 1]["date"]

profits = []
for i in range(len(be)):
    if i == 0:
        continue

    entry_position = be.iloc[i - 1]
    close_position = be.iloc[i]

    if entry_position["side"] == "BUY" and (close_position["side"] == "SELL" or
                                            close_position["side"] == "CLOSE"):

        amount = asset / entry_position["price"]
Ejemplo n.º 7
0
        if has_changed_side(side=side):
            return False
        else:
            time.sleep(1)
    return True


bitflyer = bitflyer.API(api_key=Bitflyer.Api.value.KEY.value,
                        api_secret=Bitflyer.Api.value.SECRET.value)

DATABASE = "tradingbot"
latest_side = None
while True:
    try:
        sql = "select * from entry"
        entry = repository.read_sql(database=DATABASE, sql=sql)
        if entry.empty:
            continue
        side = entry.at[0, "side"]
    except Exception:
        message.error(traceback.format_exc())
        continue

    if latest_side is None \
            or latest_side != side:
        if side == "CLOSE":
            bitflyer.close()

            if retry_sleep(secs=120, side=side):
                message.info("close retry")
                bitflyer.close()
Ejemplo n.º 8
0
            b2.Volume as v2,
            b1.Date as bb1,
            b2.Date as bb2,
            b3.Date as bb3
        from
            bitflyer_btc_ohlc_1M b1
            inner join
                bitflyer_btc_ohlc_1M b2
                on (b1.Date + interval 1 minute) = b2.Date
            inner join
                bitflyer_btc_ohlc_1M b3
                on (b3.Date + interval {back_min} minute) = b2.Date
        order by
            Date
        """.format(back_min=back_min)
be = repository.read_sql(database=database, sql=sql)

df = be["v1"]
sma = df.rolling(volume_ma).mean()[:volume_ma]
be["v1_ma"] = pd.concat([sma, df[volume_ma:]]).ewm(span=volume_ma,
                                                   adjust=False).mean()

df = be["v2"]
sma = df.rolling(volume_ma).mean()[:volume_ma]
be["v2_ma"] = pd.concat([sma, df[volume_ma:]]).ewm(span=volume_ma,
                                                   adjust=False).mean()

be["signal"] = np.where(be["v2_ma"] / be["v1_ma"] > diff_ratio, "signal", None)

be = be.drop(columns="v1_ma")
be = be.drop(columns="v2_ma")