def get_live_candles(instrument, params):
    """

    @param instrument:
    @param params:
    @return: dataframe of live candles data
    """
    client = API(access_token=access_token)
    r = instruments.InstrumentsCandles(instrument=instrument, params=params)
    client.request(r)
    candles = r.response.get("candles")
    data = []
    df1 = pd.DataFrame(candles)[['complete', 'volume', 'time']]
    df2 = pd.DataFrame(list(pd.DataFrame(candles)['mid']))
    df = pd.concat([df1, df2], axis=1)
    df.rename(mapper={
        'o': 'open',
        'h': 'high',
        'l': 'low',
        'c': 'close'
    },
              inplace=True,
              axis=1)
    df['time'] = pd.to_datetime(df['time'])
    df[['open', 'high', 'low', 'close']] = df[['open', 'high', 'low',
                                               'close']].apply(pd.to_numeric,
                                                               errors='coerce')
    return df
Exemple #2
0
def get_data(count,
             gran,
             year,
             month,
             day,
             hour,
             minute,
             second,
             inst='USD_JPY'):
    fmt = '%Y-%m-%dT%H:%M:00.000000Z'
    _from = datetime.datetime(year=year,
                              month=month,
                              day=day,
                              hour=hour,
                              minute=minute,
                              second=second).strftime(fmt)
    params = {
        "count": count,
        "granularity": gran,
        'from': _from,
    }
    r = instruments.InstrumentsCandles(instrument=inst, params=params)
    api.request(r)
    df = to_dataframe(r)
    return df
Exemple #3
0
def calculate_qty(df, signal, pair):
    position_size = nav / max_trades * 20
    print(f'position size: {position_size}')
    logging.error(f'position size: {position_size}')
    print(df.tail())
    price = df['close'].iloc[-1]
    print(f'price: {price}')
    logging.error(f'price: {price}')

    if pair in pairs_usd:
        print('pair is in pairs_usd')
        logging.error('pair is in pairs_usd')
        qty = math.floor(position_size / price)
        print(f'qty: {qty}')
        logging.error(f'qty: {qty}')
    elif pair in usd_pairs:
        print('pair is in usd_pairs')
        logging.error('pair is in usd_pairs')
        qty = math.floor(position_size)
        print(f'qty: {qty}')
        logging.error(f'qty: {qty}')
    else:
        print('pair doesn\'t have usd')
        logging.error('pair doesn\'t have usd')
        conversion_pair = conversion_pairs[pair]
        print(f'conversion pair: {conversion_pair}')
        logging.error(f'conversion pair: {conversion_pair}')
        payload = {
            'count': 1,
            'granularity': 'M1',
        }
        r = instruments.InstrumentsCandles(instrument=conversion_pair,
                                           params=payload)
        conversion_price = float(api.request(r)['candles'][-1]['mid']['c'])
        print(f'conversion price: {conversion_price}')
        logging.error(f'conversion price: {conversion_price}')

        if conversion_pair in pairs_usd:
            print('conversion pair in pairs_usd')
            logging.error('conversion pair in pairs_usd')
            price_currency_qty = position_size / conversion_price
            print(f'price currency qty: {price_currency_qty}')
            logging.error(f'price currency qty: {price_currency_qty}')
            qty = math.floor(price_currency_qty / price)
            print(f'qty: {qty}')
            logging.error(f'qty: {qty}')
        else:
            print('conversion pair not in pairs_usd')
            logging.error('conversion pair not in pairs_usd')
            price_currency_qty = position_size * conversion_price
            print(f'price currency qty: {price_currency_qty}')
            logging.error(f'price currency qty: {price_currency_qty}')
            qty = math.floor(price_currency_qty / price)
            print(f'qty: {qty}')
            logging.error(f'qty: {qty}')

    if signal == 'buy':
        return qty
    elif signal == 'sell':
        return -qty
Exemple #4
0
    def connection_historic_data(self, params):
        """
        Makes a candle download request to Oanda.

        :params (dict) is a dictionary comprised by:
            'granularity' : 'M1'
            'financial_instrument' : 'EUR_USD'
            'count': 5000
            'price': 'B' (B for Bid, A for Ask, M for Mid)
            'from': '2018-04-13T14:10:00Z'
        :return raw data from Oanda
        :rtype nested dictionaries follow structure below:
            dictionary nests list of dictionaries that nests a dictionary:
                'instrument'
                'granularity'
                'candles' --> list of dictionaries
                    'complete'
                    'volume'
                    'time'
                    'bid' --> dictionary
                        'o'
                        'h'
                        'l'
                        'c'
        """
        # For some reason Oanda (or oandapyV20) requests two instances of financial instrument as input?
        financial_instrument = params['financial instrument']
        conn_params = instruments.InstrumentsCandles(instrument=financial_instrument, params=params)
        return self.api.request(conn_params)
def insert_table(base_time, instrument, con, table_type, count):
    if decideMarket(base_time):
        sql = "select insert_time from %s_%s_TABLE where insert_time = \'%s\'" % (instrument, table_type, base_time)
        response = con.select_sql(sql)
        if len(response) == 0:
            if table_type == "1m":
                granularity = "M1"
            elif table_type == "5m":
                granularity = "M5"
            elif table_type == "1h":
                granularity = "H1"
            elif table_type == "3h":
                granularity = "H3"
            elif table_type == "8h":
                granularity = "H8"
            elif table_type == "day":
                granularity = "D"
        
            start_time = (base_time - timedelta(hours=14)).strftime("%Y-%m-%dT%H:%M:%S")
            params = {
                    "from": start_time,
                    "granularity": granularity,
                    "price": "ABM",
                    "count": count
                    }
        
            req = instruments.InstrumentsCandles(instrument=instrument, params=params)
            client.request(req)
            response = req.response
        
            if len(response) == 0:
                pass
            else:
                for candle in response["candles"]:
                    open_ask_price = candle["ask"]["o"]
                    open_bid_price = candle["bid"]["o"]
                    close_ask_price = candle["ask"]["c"]
                    close_bid_price = candle["bid"]["c"]
                    high_ask_price = candle["ask"]["h"]
                    high_bid_price = candle["bid"]["h"]
                    low_ask_price = candle["ask"]["l"]
                    low_bid_price = candle["bid"]["l"]
                    insert_time = candle["time"]
                    insert_time = insert_time.split(".")[0]
                    insert_time = insert_time + ".000000Z"
                    #print(insert_time)
                    insert_time = iso_jp(insert_time)
                    insert_time = insert_time.strftime("%Y-%m-%d %H:%M:%S")
            
                    sql = "select insert_time from %s_%s_TABLE where insert_time = \'%s\'" % (instrument, table_type, insert_time)
                    response = con.select_sql(sql)
                
                    if len(response) == 0:
                        sql = "insert into %s_%s_TABLE(open_ask, open_bid, close_ask, close_bid, high_ask, high_bid, low_ask, low_bid, insert_time) values(%s, %s, %s, %s, %s, %s, %s, %s, \'%s\')" % (instrument, table_type, open_ask_price, open_bid_price, close_ask_price, close_bid_price, high_ask_price, high_bid_price, low_ask_price, low_bid_price, insert_time)
                        print(sql)
                        try:
                            con.insert_sql(sql)
            
                        except Exception as e:
                            print(traceback.format_exc())
Exemple #6
0
def insert_new_into_table(trading_pair, time_frame):
    added_times = []
    #request data from oanda
    params = {'granularity': time_frame}
    r = instruments.InstrumentsCandles(instrument=trading_pair, params=params)
    requested_data = api.request(r)

    #prep data to push
    no_of_candles = len(requested_data['candles'])
    for i in range(no_of_candles):
        if requested_data['candles'][i]['complete'] == True:
            raw_time = requested_data['candles'][i]['time']
            formatted_time = datetime.strptime(raw_time,
                                               '%Y-%m-%dT%H:%M:%S.000000000Z')
            formatted_time = formatted_time + timedelta(hours=3)
            temp = str(formatted_time)[:-3]
            formatted_time = temp.replace('-', '.')

            table_name = '{}_{}'.format(time_frame, trading_pair)
            #check if time needs to be added
            if time_query_check(table_name, formatted_time) == []:
                raw_data = requested_data['candles'][i]['mid']
                o = raw_data['o']
                h = raw_data['h']
                l = raw_data['l']
                c = raw_data['c']
                insert_stuff(table_name, (formatted_time, o, h, l, c))
                added_times.append(formatted_time)
    return added_times
Exemple #7
0
 def get_candles(self, _from, count, granularity, instrument):
     params = {"from": _from, "count": count, "granularity": granularity}
     r = instruments.InstrumentsCandles(instrument=instrument,
                                        params=params)
     data = self.client.request(r)
     #print(data)
     return data
Exemple #8
0
def get_price_data(pair, config_file, output, **kwargs):
    """Get data from Oanda and put in CSV.

    Parameters
    ----------
    pair: str
        The instrument pair in which to fetch prices.
    config_file : str
        Location of configuration file.
    output: str
        Location and name of output .csv file.

    """
    conf = get_config(config_file)
    kwargs['price'] = 'BA'

    r = instruments.InstrumentsCandles(instrument=pair, params=kwargs)
    api = API(access_token=conf['token'])
    api.request(r)

    prices = []
    for _ in r.response['candles']:
        prices.append([
            _['time'], _['bid']['c'], _['ask']['c'],
            float(_['ask']['c']) - float(_['bid']['c'])
        ])

    df = pd.DataFrame(prices)
    df.columns = ['time', 'bid', 'ask', 'spread']
    df.to_csv(output, sep='\t', index=False)
def get_exrate_as_df(instrument='EUR_USD',
                     granularity='D',
                     from_=None,
                     to='2019-03-01',
                     count=100):
    if from_ is None:
        params = {
            'granularity': granularity,
            'to': to,
            'count': count,
        }
    else:
        params = {
            'granularity': granularity,
            'from': from_,
            'to': to,
        }
    api = API(access_token=ACCESS_TOKEN)
    r = instruments.InstrumentsCandles(instrument=instrument, params=params)
    api.request(r)
    data = []
    for row in r.response['candles']:
        data.append([
            row['time'], row['mid']['o'], row['mid']['h'], row['mid']['l'],
            row['mid']['c'], row['volume']
        ])
    df = pd.DataFrame(data)
    df.columns = ['time', 'open', 'high', 'low', 'close', 'volume']
    df = df.set_index('time')
    df.index = pd.to_datetime(df.index)
    df = df.astype(float)

    return df
Exemple #10
0
        def candle_data(self, symbol, granularity, de, para):
                """ Candle data for symbols """

                params = {"from": de,
                "granularity": granularity, 
                "to": para,
                "alignmentTimezone": "Europe/Moscow", 
                }

                r = instruments.InstrumentsCandles(instrument=symbol, params=params)
                data = api.request(r)
                clean = [{'time':i['time'],"open":i['mid']['o'],
                        "close":i['mid']['c'],'high':i['mid']['h'],
                        'low':i['mid']['l']} for i in data['candles']]
        
                df = pd.DataFrame(clean)
                
                df.set_index('time',inplace=True)
                df.index = [ parse(i).strftime('%Y-%m-%d') for i in df.index ]
                df.index = pd.to_datetime(df.index)
                
                df = df.convert_objects(convert_numeric=True)
                df['asset'] = symbol

                return df
Exemple #11
0
    def get_candles(self, instrument: str, date_from: datetime,
                    date_to: datetime, granularity: str):
        timestamp_from = math.floor(date_from.timestamp())
        timestamp_to = math.floor(date_to.timestamp())

        granularity_s = self.__get_granularity_s(granularity)
        candles = []
        while timestamp_to - timestamp_from > 0:
            _from = timestamp_from
            _to = timestamp_from + 5000 * granularity_s
            if _to > timestamp_to:
                _to = timestamp_to
            params = {
                "from": datetime.utcfromtimestamp(_from).isoformat() + "Z",
                "to": datetime.utcfromtimestamp(_to).isoformat() + "Z",
                "granularity": granularity
            }
            r = instruments.InstrumentsCandles(instrument, params)
            resp = self.__api.request(r)
            candles += resp["candles"]
            timestamp_from = _to
        data = []
        for candle in candles:
            data.append([
                datetime.fromisoformat(candle["time"].split(".")[0]),
                candle["mid"]["o"], candle["mid"]["h"], candle["mid"]["l"],
                candle["mid"]["c"], candle["volume"]
            ])
        df = pd.DataFrame(data)
        df.columns = ["DateTime", "Open", "High", "Low", "Close", "Volume"]
        df["Open"] = df["Open"].astype(float)
        df["High"] = df["High"].astype(float)
        df["Low"] = df["Low"].astype(float)
        df["Close"] = df["Close"].astype(float)
        return df
Exemple #12
0
def candles(inst, granularity, count, From, to, price, nice, access_token):
    api = API(access_token=access_token)

    def check_date(s):
        dateFmt = "[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}Z"
        if not re.match(dateFmt, s):
            raise ValueError("Incorrect date format: ", s)

        return True

    if inst:
        params = {}
        if granularity:
            params.update({"granularity": granularity})
        if count:
            params.update({"count": count})
        if From and check_date(From):
            params.update({"from": From})
        if to and check_date(to):
            params.update({"to": to})
        if price:
            params.update({"price": price})
        for i in inst:
            r = instruments.InstrumentsCandles(instrument=i, params=params)
            rv = api.request(r)
            kw = {}
            if nice:
                kw = {"indent": nice}
            # print("{}".format(json.dumps(rv, **kw)))
            return rv
Exemple #13
0
def show_candles(accountID, instrument, other_args: List[str]):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="candles",
        description="Display Candle Data",
    )
    parser.add_argument(
        "-g",
        "--granularity",
        dest="granularity",
        action="store",
        type=str,
        default="D",
        required=False,
        help=
        "The timeframe to get for the candle chart (Seconds: S5, S10, S15, S30 "
        +
        "Minutes: M1, M2, M4, M5, M10, M15, M30 Hours: H1, H2, H3, H4, H6, H8, H12 "
        + "Day (default): D, Week: W Month: M",
    )
    parser.add_argument(
        "-c",
        "--count",
        dest="candlecount",
        action="store",
        default=180,
        type=int,
        required=False,
        help="The number of candles to retrieve. Default:180 ",
    )

    ns_parser = parse_known_args_and_warn(parser, other_args)
    if not ns_parser:
        return

    parameters = {}
    parameters["granularity"] = ns_parser.granularity
    parameters["count"] = ns_parser.candlecount
    try:
        instrument = format_instrument(instrument, "_")
        request = instruments.InstrumentsCandles(instrument, params=parameters)
        response = client.request(request)
        process_candle_response(response)
        oanda_fix_date(".temp_candles.csv")
        df = pd.read_csv(".candles.csv", index_col=0)
        df.index = pd.to_datetime(df.index)
        df.columns = ["Open", "High", "Low", "Close", "Volume"]
        if gtff.USE_ION:
            plt.ion()
        mpf.plot(
            df,
            type="candle",
            style="charles",
            volume=True,
            title=f"{instrument} {ns_parser.granularity}",
        )
        print("")
    except V20Error as e:
        d_error = eval(e.msg)
        print(d_error["errorMessage"], "\n")
Exemple #14
0
 def get_candle(self, instrument='EUR_USD', count=2, granularity='M1'):
     r = instruments.InstrumentsCandles(instrument=instrument,
                                        params={
                                            'count': count,
                                            'granularity': granularity
                                        })
     candleprice = self.client.request(r)
     completed = False
     for count in candleprice["candles"]:
         if count['complete']:
             volume = float(count['volume'])
             high = float(count['mid']['h'])
             low = float(count['mid']['l'])
             close = float(count['mid']['c'])
             date = count['time']
             times = self.reverse_format_func(date)
             if len(self.times) == 0:
                 completed = True
                 self.times = [times]
                 self.last_close = close
                 self.last_volume = volume
             elif times != self.times[-1]:
                 completed = True
                 self.times.append(times)
                 self.liste_to_evol(high=high,
                                    low=low,
                                    close=close,
                                    volume=volume)
     return completed
Exemple #15
0
def connect_to_api():
    client = oandapyV20.API(access_token= ACCESS_TOKEN)
    params = {'accountId' : ACCOUNT_ID, 'instruments' : INSTRUMENTS, 'granularity': granularity}
    data_request = instruments.InstrumentsCandles(instrument = INSTRUMENTS, params = params)
    client.request(data_request)
    response = data_request.response
    return response
    def get_instruments_all(self,
                            instruments_list,
                            from_date,
                            to_date='',
                            granularity="D",
                            price="MBA"):
        data = {}
        params = {}
        params['granularity'] = granularity
        params['price'] = price
        if from_date != '':
            params['from'] = from_date
        if to_date != '':
            params['to'] = to_date
        else:
            now = datetime.datetime.now()
            now = now.strftime('%Y-%m-%d')
            params['to'] = now

        client = oandapyV20.API(access_token=self.__token)

        for i in range(len(instruments_list)):
            try:
                r = instruments.InstrumentsCandles(
                    instrument=instruments_list[i], params=params)
                json_response = client.request(r)
                data[instruments_list[i]] = self.get_tot_trade(json_response)
            except:
                continue
        return (data)
Exemple #17
0
    def main(self):
        def check_date(s):
            dateFmt = "[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}Z"
            if not re.match(dateFmt, s):
                raise ValueError("Incorrect date format: ", s)

            return True

        if self.clargs.instruments:
            params = {}
            if self.clargs.granularity:
                params.update({"granularity": self.clargs.granularity})
            if self.clargs.count:
                params.update({"count": self.clargs.count})
            if self.clargs.From and check_date(self.clargs.From):
                params.update({"from": self.clargs.From})
            if self.clargs.to and check_date(self.clargs.to):
                params.update({"to": self.clargs.to})
            if self.clargs.price:
                params.update({"price": self.clargs.price})
            for i in self.clargs.instruments:
                r = instruments.InstrumentsCandles(instrument=i, params=params)
                rv = self.api.request(r)
                kw = {}
                if self.clargs.nice:
                    kw = {"indent": self.clargs.nice}
                print("{}".format(json.dumps(rv, **kw)))
Exemple #18
0
def get_sequence_candles(instrument, granularity, count, da=daily_alignment):
    env = yaml.safe_load(open('/seq/seq5/configs/env.yaml', 'r'))
    client = oandapyV20.API(access_token=env['client'])
    params = {
        'count': count,
        'granularity': granularity,
        'price': 'M',
        'alignmentTimezone': 'UTC',  #'America/Los_Angeles',
        'dailyAlignment': da
    }

    r = instruments.InstrumentsCandles(instrument=instrument, params=params)
    coll = client.request(r)
    # Remove last candle if not complete.
    if coll['candles'][-1]['complete'] == False:
        coll['candles'].pop()
    # Assemble Dataframe
    high = []
    low = []
    close = []
    timestamp = []
    for i in range(len(coll['candles'])):
        high.append(float(coll['candles'][i]['mid']['h']))
        low.append(float(coll['candles'][i]['mid']['l']))
        close.append(float(coll['candles'][i]['mid']['c']))
        timestamp.append(coll['candles'][i]['time'])
    # Assemble DataFrame.  Cast Values.
    df = pd.DataFrame(pd.to_datetime(timestamp))
    df.columns = ['timestamp']
    df['high'] = pd.to_numeric(high)
    df['low'] = pd.to_numeric(low)
    df['close'] = pd.to_numeric(close)
    return df
def f_descarga_precios(date, instrument):
    """
    Parameters
    ---------
    instrument: str : instrumento del precio que se requiere
    date : date : fecha del dia del precio

    Returns
    ---------
    prices: : precios del activo descargado.

    Debuggin
    ---------
        instrument : str : cadena de texto con 'EUR_USD'
        date = pd.to_datetime("2019-07-06 00:00:00")
    """

    # Inicializar api de OANDA
    api = API(environment="practice", access_token='107596e9d65c' + '1bbc9175953d917140' + '12-f975c6201dddad03ac1592232c0ea0ea',)

    # Convertir en string la fecha
    fecha = date.strftime('%Y-%m-%dT%H:%M:%S')
    # Parametros para Oanda
    r = instruments.InstrumentsCandles(instrument=instrument,
                                       params={"count": 1, "granularity": 'S10', "price": "M", "dailyAlignment": 16, "from": fecha})
    # Descargar
    response = api.request(r)
    # En fomato candles
    prices = response.get("candles")
    # Regresar el precio de apertura
    return prices
Exemple #20
0
    def __init__(self, instrument, granularity, units, clargs):
        self.accountID, token = authentication()
        self.client = API(access_token=token)
        self.units = units
        self.clargs = clargs
        self.pt = PriceTable(instrument, granularity)
        # fetch First Candle data
        params = {"count": 1, "from": self.clargs.Orbdate}
        r = instruments.InstrumentsCandles(instrument=instrument,
                                           params=params)
        rv = self.client.request(r)
        if len(rv) == 0:
            logger.error(
                "No candle data available for specified date:{d}".format(
                    d=self.clargs.Orbdate))

        # and calculate indicators
        for crecord in rv['candles']:
            if crecord['complete'] is True:
                self.high = float(crecord['mid']['h'])
                self.low = float(crecord['mid']['l'])
        ORBdetails = ORB(self.pt, self.client, self.high, self.low)
        self.pt.setHandler("onAddItem", ORBdetails.calculate)
        self.indicators = [ORBdetails]
        self.state = NEUTRAL  # overall state based on calculated indicators
        self.unit_ordered = False

        self._botstate()
    def __init__(self, instrument, granularity, units, clargs):
        self.accountID, token = exampleAuth()
        self.client = API(access_token=token)
        self.units = units
        self.clargs = clargs
        self.pt = PriceTable(instrument, granularity)
        mavgX = MAx(self.pt, clargs.shortMA, clargs.longMA, clargs.SOK,
                    clargs.SOD, clargs.SOF)
        self.pt.setHandler("onAddItem", mavgX.calculate)
        self.indicators = [mavgX]
        self.state = NEUTRAL  # overall state based on calculated indicators

        # fetch initial historical data
        params = {"granularity": granularity, "count": self.clargs.longMA}
        r = instruments.InstrumentsCandles(instrument=instrument,
                                           params=params)
        rv = self.client.request(r)
        # and calculate indicators
        for crecord in rv['candles']:
            if crecord['complete'] is True:
                # def addItem(self, dt, ao, ah, al, ac, av, bo, bh, bl, bc, bv):
                self.pt.addItem(crecord['time'], float(crecord['mid']['o']),
                                float(crecord['mid']['h']),
                                float(crecord['mid']['l']),
                                float(crecord['mid']['c']),
                                int(crecord['volume']),
                                float(crecord['mid']['o']),
                                float(crecord['mid']['h']),
                                float(crecord['mid']['l']),
                                float(crecord['mid']['c']),
                                int(crecord['volume']))

        self._botstate()
Exemple #22
0
def get_candles(granularity, instrument="USD_CAD", count=100):
    '''
    Returns candlestick information based on given parameters.
    Information is returned as a pandas df
    '''

    params = {"count": count, "granularity": granularity}

    oanda, __ = connect_to_server()
    r = instruments.InstrumentsCandles(instrument, params=params)
    oanda.request(r)
    candles = r.response['candles']

    for i in candles:
        i.pop('complete')
        olhc = i.pop('mid')
        i['Date'] = i.pop('time')
        i['Volume'] = i.pop('volume')
        i['Open'] = float(olhc['o'])
        i['High'] = float(olhc['h'])
        i['Low'] = float(olhc['l'])
        i['Close'] = float(olhc['c'])
        i['Volume'] = float(i['Volume'])

    df = pd.DataFrame(candles)
    df['Datetime'] = pd.DatetimeIndex(df['Date'])
    df = df.set_index('Datetime')
    df = df.drop(['Date'], axis=1)
    # csv_for_testing()
    return df
Exemple #23
0
    def get_last_hour(self, which=1):

        last_hour = pd.DataFrame()

        for j in range(0, len(self.instrument)):

            params = {}

            params.update({'granularity': 'M5'})
            params.update({'count': 2})
            params.update({'price': 'BA'})
            r = instruments.InstrumentsCandles(instrument=self.instrument[j],
                                               params=params)
            rv = self.api.request(r)

            dict = {}

            for i in range(2):
                df = pd.DataFrame.from_dict(rv['candles'][:][i])

                df = df.transpose()

                spread = float(df.loc['ask'].c) - float(df.loc['bid'].c)

                list = df.loc['ask'][['o', 'h', 'l', 'c', 'time']]
                date = df.loc['time'].c
                vol = df.loc['volume'].c

                dict[i] = {
                    'date': date,
                    'open': float(list.o),
                    'high': float(list.h),
                    'low': float(list.l),
                    'close': float(list.c),
                    'AskVol': float(vol),
                    'spread': spread,
                    'symbol': self.instrument[j]
                }

            df = pd.DataFrame.from_dict(dict)
            df = df.transpose()

            df = df.set_index(pd.to_datetime(df.date))

            df = df[[
                'open', 'high', 'low', 'close', 'AskVol', 'spread', 'symbol'
            ]]

            last_hour = last_hour.append(df.iloc[which])

            last_hour = last_hour[['close', 'symbol']]

        time = last_hour.index[0]
        values = last_hour.close.values
        symbols = last_hour.symbol.values
        append = pd.DataFrame(data=[values], columns=symbols, index=[time])

        self.hist_data = self.hist_data.append(append)

        self.hist_data.to_csv('Data/Composite_Prices.csv')
Exemple #24
0
def main():
    access_token = "df36fd83bc0d3b33010ebbea7feb99d7-5849f313292879ab44e0a824de58e1ad"
    api = API(access_token=access_token, environment="practice")
    # count = 2000
    count = 100

    params = {
        "count": count,  # 足3本取得
        "granularity": "M5",  # 1分足を取得
        "price": "B",  # Bidを取得
    }
    instruments_candles = instruments.InstrumentsCandles(instrument="GBP_USD",
                                                         params=params)

    try:
        api.request(instruments_candles)
        response = instruments_candles.response
        df = pd.DataFrame([candle["bid"] for candle in response["candles"]],
                          dtype=np.float64)
        df['v'] = [candle["volume"] for candle in response["candles"]]
        df.columns = ['Open', 'High', 'Low', 'Close', 'Volume']
        df['date'] = [candle["time"] for candle in response["candles"]]
        df['date'] = pd.to_datetime(df['date'])
        df.set_index('date', inplace=True)
        # print(df)
        for i in range(int(count / 10)):
            mpf.plot(df[i * 10:(i + 1) * 10],
                     type='candle',
                     style='nightclouds',
                     savefig=f'data/candles{i}.png')
        # mpf.show()

    except V20Error as e:
        print("Error: {}".format(e))
Exemple #25
0
def candlestickinfo(candlecount, granularity):
    parameters = {"count": candlecount, "granularity": granularity}

    info = instruments.InstrumentsCandles(instrument="EUR_USD",
                                          params=parameters)
    api.request(info)
    return info.response
def get_candles(instrument, params):
    _conf = PyOandaConfig()
    _api = API(access_token=_conf.access_token, environment="practice")
    _request = instruments.InstrumentsCandles(instrument=instrument, params=params)
    _api.request(_request)

    return _request.response
Exemple #27
0
    def historical_klines(self, forex_pair, num_of_candles, interval):

        import oandapyV20.endpoints.instruments as instruments

        parameters = {"count": num_of_candles, "granularity": interval}
        r = instruments.InstrumentsCandles(instrument=forex_pair, params=parameters)
        self.client.request(r)
        forex_pair_data_raw = r.response

        # OHLC
        flag_historical = True
        idx_historical = 0

        while flag_historical:

            self.open_prices.append(float(forex_pair_data_raw["candles"][idx_historical]["mid"]["o"]))
            self.high_prices.append(float(forex_pair_data_raw["candles"][idx_historical]["mid"]["h"]))
            self.low_prices.append(float(forex_pair_data_raw["candles"][idx_historical]["mid"]["l"]))
            self.close_prices.append(float(forex_pair_data_raw["candles"][idx_historical]["mid"]["c"]))

            self.date_time.append(forex_pair_data_raw["candles"][idx_historical]["time"][: -11])

            if idx_historical == num_of_candles - 1:
                flag_historical = False

            idx_historical += 1

        self.red_green_candles = ["Green" if x[0] < x[1] else "Red" for x in zip(self.open_prices, self.close_prices)]

        self.candles_size = [round((((x[1] - x[0]) * 100) / x[0]), 3) for x in zip(self.open_prices, self.close_prices)]
def get_candles_dataframe(accountID, instrument, parameters):
    if not parameters:
        parameters = {
            "granularity": "D",
            "count": "1500",
        }
    try:
        request = instruments.InstrumentsCandles(instrument, params=parameters)
        response = client.request(request)
        candles_data = []
        for i in range(len(response["candles"])):
            candles_data.append({
                "Date":
                response["candles"][i]["time"][:10] + " " +
                response["candles"][i]["time"][11:19],
                "Open":
                float(response["candles"][i]["mid"]["o"]),
                "High":
                float(response["candles"][i]["mid"]["h"]),
                "Low":
                float(response["candles"][i]["mid"]["l"]),
                "Close":
                float(response["candles"][i]["mid"]["c"]),
                "Volume":
                response["candles"][i]["volume"],
            })
        df = pd.DataFrame(candles_data)
        df.set_index("Date", inplace=True)
        df.index = pd.to_datetime(df.index)
        return df
    except V20Error as e:
        # pylint: disable=W0123
        d_error = eval(e.msg)
        print(d_error["errorMessage"], "\n")
Exemple #29
0
def get_currency_bars(ticker, granularity, numBars=1):
    """
	returns a dataframe object that has the specified currency's Current price,Open,High,Low,Close Values
	for the specified Granularity. Default number of bars is 1. 
	"""
    #Set up Parameters
    inParams = {"count": numBars, "granularity": granularity}
    #retrieve data from network
    candle_get = instruments.InstrumentsCandles(instrument=ticker,
                                                params=inParams)
    client.request(candle_get)
    #Flatten the data recived from network and set datetime index
    norm_data = json_normalize(candle_get.response['candles'])
    norm_data.set_index(norm_data['time'].apply(pd.to_datetime), inplace=True)
    #Create the dataframe you will return
    ret_df = pd.DataFrame(
        np.zeros((numBars, 6)),
        index=norm_data['time'].apply(pd.to_datetime),
        columns='Open High Low Close Volume Complete'.split())
    #Assign corresponding Columns and return the dataframe!
    ret_df['Open'] = norm_data['mid.o']
    ret_df['High'] = norm_data['mid.h']
    ret_df['Low'] = norm_data['mid.l']
    ret_df['Close'] = norm_data['mid.c']
    ret_df['Volume'] = norm_data['volume']
    ret_df['Complete'] = norm_data['complete']

    return ret_df
Exemple #30
0
    def get_historical_ohlc(self, instrument=INSTRUMENT, granularity=GRANULARITY, count=5000):
        """

        :param instrument:
        :param from_date:
        :param to_date:
        :return:
        """

        # get historical price data from OANDA API
        params = {
            "granularity": granularity,
            "count": count
        }
        hist_data = instruments.InstrumentsCandles(instrument,  params)
        hist_data = client.request(hist_data)

        # save the historical data
        collection = db['historical_ohlc']
        collection.insert_one(hist_data)

        del hist_data['_id']
        print(hist_data)
        print(type(hist_data))


        return hist_data