예제 #1
0
def fill_blank(now, candlestick, assignor):
    date = assignor.nextDate(candlestick.getDate())
    out = ''
    while now != date:
        cs = Candlestick(date, candlestick.getClose())
        out += cs.toString()
        date = assignor.nextDate(date)
    return out
예제 #2
0
def __on_rtvolume_event(msg):
    try:
        if (msg.typeName == 'tickString'):
            if msg.tickType == 48:
                tick_data = msg.value.split(';')
                last_price = float(tick_data[0])
                traded_volume = int(tick_data[1])
                trade_time = dt.datetime.fromtimestamp(
                    int(tick_data[2]) / 1000.0)
                # daily_volume = tick_data[3]
                # vwap = tick_data[4]
                # single_market_maker = (tick_data[5] == 'true')

            # Check if a new dataset has to be created
            if msg.tickerId not in candlestick_data.keys():
                candlestick_data[msg.tickerId] = []

            # Check if a new candlestick shall be created
            if ((not candlestick_data[msg.tickerId]) or
                (trade_time > candlestick_data[msg.tickerId][-1].end_time)):
                # Print last finished candlestick
                if (candlestick_data[msg.tickerId]):
                    print(candlestick_data[msg.tickerId][-1])
                candlestick_data[msg.tickerId].append(
                    Candlestick(start_time=trade_time,
                                duration=dt.timedelta(minutes=1),
                                last_price=last_price,
                                volume=traded_volume))
            else:
                candlestick_data[msg.tickerId][-1].add_market_data(
                    dt.datetime.now(), last_price, traded_volume)
    except Exception as e:
        print_exception()
예제 #3
0
def __on_historicaldata_event(msg):
    try:
        # Check if a new dataset has to be created
        if msg.reqId not in candlestick_data.keys():
            candlestick_data[msg.reqId] = []

        # Check if all the data has been received already (in that case,
        # received data will be -1:
        if msg.open != -1:
            candlestick_data[msg.reqId].append(
                Candlestick(start_time=dt.datetime.strptime(
                    msg.date, '%Y%m%d %H:%M:%S'),
                            duration=dt.timedelta(minutes=1),
                            open=msg.open,
                            high=msg.high,
                            low=msg.low,
                            close=msg.close,
                            volume=msg.volume))
        else:
            # All the data has been received, cancel request
            con.cancelHistoricalData(msg.reqId)
            print('All the requested historical data has been received')

            # Suscribe to realtime ticks data. For forex we need to use the
            # midpoint, and for the rest of contracts we use RTvolume
            if contract.m_secType == 'CASH':
                con.reqMktData(msg.reqId, contracts_dict[msg.reqId], '', False)
            else:
                con.reqMktData(msg.reqId, contracts_dict[msg.reqId],
                               '233,mdoff', False)
    except Exception as e:
        print_exception()
예제 #4
0
def make_csv(f_input, f_output, frequency='1m'):
    assignor = Assignor(frequency)
    candlestick = None
    f_w = open(f_output, 'w')
    for line in open(f_input, 'r'):
        unixtime, price, volume = map(float, line.strip().split(','))
        date = assignor.convertUnixtime(unixtime)
        if candlestick is None:
            candlestick = Candlestick(date)
        elif date != candlestick.getDate():
            f_w.write(candlestick.toString())
            f_w.write(fill_blank(date, candlestick, assignor))
            candlestick = Candlestick(date, candlestick.getClose())
        candlestick.set(price, volume)
    f_w.write(candlestick.toString())
    f_w.close()
예제 #5
0
    def __init__(self, pair, period, exchange_interface):

        self.pair = pair
        self.indicators = StrategyAnalyzer()
        self.data = []

        # Query the data to fill our chart truncate it to 'length' elements
        raw_data = exchange_interface.get_historical_data(
            pair, interval=Chart.period_to_integer(period))

        for datum in raw_data:
            stick = Candlestick(time=datum[0],
                                open=datum[1],
                                high=datum[2],
                                low=datum[3],
                                close=datum[4],
                                price_average=(datum[2] + datum[3]) / 2.)
            self.data.append(stick)
예제 #6
0
    def __init__(self,
                 exchange,
                 pair,
                 period,
                 start_time=time() - 100000,
                 end_time=time(),
                 backtest=True,
                 length=9999999):

        self.pair = pair
        self.period = period
        self.backtest = backtest
        self.length = length

        self.startTime = start_time
        self.endTime = end_time

        self.data = []

        with open("bot/secrets.json") as secrets_file:
            secrets = json.load(secrets_file)
            secrets_file.close()

        if exchange == "poloniex":
            self.conn = Poloniex(secrets['poloniex_key'],
                                 secrets['poloniex_secret'])

            if backtest:
                rawdata = self.conn.api_query(
                    "get_chart_data", {
                        "currencyPair": self.pair,
                        "start": self.startTime,
                        "end": self.endTime,
                        "period": self.period
                    })
                for datum in rawdata:
                    if datum['open'] and datum['close'] and datum[
                            'high'] and datum['low']:
                        self.data.append(
                            Candlestick(self.period, datum['open'],
                                        datum['close'], datum['high'],
                                        datum['low'],
                                        datum['weightedAverage']))

        if exchange == "bittrex":
            self.connv1 = Bittrex(secrets['bittrex_key'],
                                  secrets['bittrex_secret'],
                                  api_version=API_V1_1)
            self.conn = Bittrex(secrets['bittrex_key'],
                                secrets['bittrex_secret'],
                                api_version=API_V2_0)

            if backtest:
                rawdata = self.conn.get_candles(
                    market=self.pair,
                    tick_interval=self.period)['result'][:length]

                for i in range(len(rawdata)):
                    datum = rawdata[i]
                    stick = Candlestick(period_map[self.period], datum['O'],
                                        datum['C'], datum['H'], datum['L'],
                                        (datum['O'] + datum['C']) / 2.)
                    stick.time = i
                    self.data.append(stick)
    def _ui(self):
        l1 = QVBoxLayout()
        self.setLayout(l1)
        l1.setContentsMargins(0, 0, 0, 0)

        self.canvas = scene.SceneCanvas(title="",
                                        show=False,
                                        create_native=False,
                                        px_scale=1,
                                        bgcolor=Color("#101010"),
                                        dpi=None)
        self.canvas.create_native()
        l1.addWidget(self.canvas.native, )  # not set alignment

        #
        grid = self.canvas.central_widget.add_grid()
        grid.spacing = 0

        yaxis = scene.AxisWidget(
            orientation='left',
            # axis_label='Y Axis',
            axis_font_size=12,
            axis_label_margin=50,
            tick_label_margin=5)
        yaxis.width_max = 50
        yaxis.stretch = (0.05, 1)
        grid.add_widget(yaxis, row=0, col=0)

        xaxis = scene.AxisWidget(
            orientation='bottom',
            axis_label='X Axis',
            axis_font_size=12,
            axis_label_margin=100,
            tick_label_margin=10,
        )

        xaxis.height_max = 100
        xaxis.stretch = (1, .1)
        grid.add_widget(xaxis, row=1, col=1)

        view: scene.ViewBox = grid.add_view(row=0, col=1, border_color='white')
        view.camera = scene.PanZoomCamera()
        view.border_color = "#ffffff"

        xaxis.link_view(view)
        yaxis.link_view(view)

        global df
        # Candlestick
        kline1 = Candlestick(borderwidth=.2, padding=.1)
        kline1.set_data(df.x.values, df.o.values, df.h.values, df.l.values,
                        df.c.values)
        view.add(kline1)

        # MA(CLOSE,22)
        try:
            import talib
            pos = np.empty((len(df), 2), dtype=np.float32)
            pos[:, 0] = np.arange(len(df))
            pos[:, 1] = talib.MA(df.c.values, timeperiod=22)
            ma_line = scene.visuals.Line(pos,
                                         color=(1, 1, 1, 1),
                                         method='gl',
                                         width=1)
            view.add(ma_line)
        except:
            pass

        # view.camera.rect = (0, 0, 800, 7000)
        view.camera.set_range()