def bulkloadlivedatabytime(instrument, granularity, start):
    # load data from start date to now
    # example: bulkloadlivedatabytime('EUR_GBP','M15','2017-08-07T00:00:00Z')
    client = API(access_token=access_token)
    time = []
    value = []
    stop_date = datetime.utcnow()
    start_date = datetime.strptime(start, "%Y-%m-%dT%H:%M:%SZ")
    diff = stop_date - start_date
    mins = int(diff.total_seconds() / (60 * 15))
    print(mins)
    stop = stop_date.strftime("%Y-%m-%dT%H:%M:%SZ")
    print(stop)
    params = {
        "from": start,
        "to": stop,
        "granularity": granularity,
        "count": mins
    }
    for r in InstrumentsCandlesFactory(instrument=instrument, params=params):
        client.request(r)
        data = r.response.get('candles')

        for k in range(len(data)):
            time.append(data[k]['time'])
            value.append(data[k]['mid']['c'])
    d = {'time': time, instrument: value}
    df = pandas.DataFrame(data=d)
    return df
示例#2
0
 def histPrice(self, broker, accountID, pair, t0, t1=None, gran='M10'):
     if broker == 'oanda':
         t0Str = t0.strftime('%Y-%m-%dT%H:%M:%S') + 'Z'
         if t1 == None:
             paramshist = \
                 {
                     "from": str(t0Str),
                     "granularity": gran
                 }
         else:
             t1Str = t1.strftime('%Y-%m-%dT%H:%M:%S') + 'Z'
             paramshist = \
                 {
                     "from": str(t0Str),
                     "to": str(t1Str),
                     "granularity": gran
                 }
         priceH = pd.DataFrame({
             'c': [],
             'h': [],
             'l': [],
             'o': []
         },
                               index=[])
         client = API(access_token=cfg.brokerList['oanda']['token'])
         for r in InstrumentsCandlesFactory(instrument=pair,
                                            params=paramshist):
             rv = dict(client.request(r))["candles"]
             for candle in rv:
                 print(candle)
                 priceH.loc[pd.Timestamp(candle["time"],
                                         tzinfo='UTC')] = candle["mid"]
         return (priceH)
示例#3
0
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
示例#4
0
def TransactionsTransactionDetails(access_token, accountID, transactionID):
    'Get the details of a single Account Transaction.'
    r = transactions.TransactionDetails(accountID=accountID,
                                        transactionID=transactionID)
    client = API(access_token=access_token)
    client.request(r)
    return readable_output(Munch(r.response)), Munch(r.response)
示例#5
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)
示例#6
0
def InstrumentsPositionBook(access_token, instrument, params):  # check
    'Get positionbook data for a specified Instrument.'
    r = instruments.InstrumentsPositionBook(instrument=instrument,
                                            params=params)
    client = API(access_token=access_token)
    client.request(r)
    return readable_output(Munch(r.response)), Munch(r.response)
    def start(self, ignore_heartbeat=False, **kwargs):
        # We want the heartbeats by default
        client = API(access_token=self.access_token,
                     environment=self.environment)

        params = {"instruments": kwargs["instruments"]}
        r = pricing.PricingStream(accountID=kwargs['accountId'], params=params)
        logging.info("Request is: %s with instruments: %s", r,
                     params['instruments'])

        while True:
            try:
                for tick in client.request(r):
                    logging.info("TICK: %s", tick)
                    self.on_success(V1compat(tick))

            except V20Error as e:
                # catch API related errors that may occur
                logger.error("V20Error: %s", e)
                break

            except ConnectionError as e:
                logger.error("Connection Error: %s", e)
                break

            except StreamTerminated as e:
                logger.error("StreamTerminated exception: %s", e)
                break

            except Exception as e:
                exc_type, exc_obj, exc_tb = sys.exc_info()
                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                logger.error("Unknown exception: %s | %s | %s", exc_type,
                             fname, exc_tb.tb_lineno)
                break
示例#8
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
示例#9
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()
示例#10
0
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
def connect_v20(access_token, accountID, instruments):
    api = API(access_token=access_token, environment="practice")
    s = PricingStream(accountID=accountID, params={"instruments": instruments})
    response = api.request(s)
    try:
        n = 0
        for R in api.request(s):
            # print (msg['type'])
            if R['type'] == 'HEARTBIT':
                print(json.dumps(R['type'], indent=2),
                      json.dumps(R['type']['time'], indent=2))
            if R['type'] == 'PRICE':
                instrument = json.loads(json.dumps(R['instrument'], indent=2))
                status = json.loads(json.dumps(R['status'], indent=2))
                timestamp = json.loads(json.dumps(R['time'], indent=2))
                closeoutBid = json.loads(json.dumps(R['closeoutBid'],
                                                    indent=2))
                closeoutAsk = json.loads(json.dumps(R['closeoutAsk'],
                                                    indent=2))
                askBook = json.loads(json.dumps(R['asks'], indent=2))
                # influx_record(R['type'])
                print(instrument, timestamp, closeoutBid, closeoutAsk)
                position_open(instrument, closeoutBid, closeoutAsk)
                # for line in askBook:
                #     price = json.loads(json.dumps(line["price"], indent=2))
                #     liquidity = json.loads(json.dumps(line["liquidity"], indent=2))
                #     print (price,liquidity)
                # return instrument,closeoutBid, closeoutAsk
            # n += 1
            # if n > 125:
            #     s.terminate("maxrecs received: {}".format(MAXREC))
    except V20Error as e:
        print("Error: {}".format(e))
    def __init__(self, granularity):
        """"コンストラクタ
        引数:
            dt (str): datetime formatted by DT_FMT.
        戻り値:
            tf_dt (str): changed datetime.
        """

        self.__CANDLES = "candles"
        self.__MID = "mid"
        self.__O = "o"
        self.__H = "h"
        self.__L = "l"
        self.__C = "c"

        self.__TIME = "time"
        self.__VOLUME = "volume"
        self.__OPEN = "open"
        self.__HIGHT = "high"
        self.__LOW = "low"
        self.__CLOSE = "close"

        self.__DT_FMT = "%Y-%m-%dT%H:%M:00.000000000Z"
        self.__GRANULARITY = granularity

        self.__df = []

        self.__api = API(access_token=ya.access_token,
                         environment=oc.OandaEnv.PRACTICE)
示例#13
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))
示例#14
0
    def order(self, quote, precision_digits, bet_size, currency, profit, stop):
        tp = {"timeInForce": "GTC", "price": str(round(abs(profit), precision_digits))}
        sl = {"timeInForce": "GTC", "price": str(round(abs(stop), precision_digits))}

        order = {"order": {"units": bet_size, "instrument": currency, "timeInForce": "FOK", "type": "LIMIT",
                           "positionFill": "DEFAULT", "price": str(round(quote, precision_digits)),
                           'takeProfitOnFill': tp,
                           'stopLossOnFill': sl}}

        # client
        api = API(access_token=self.token)

        # create and process order requests
        r = orders.OrderCreate(accountID=self.account_id, data=order)
        print("processing : {}".format(r))
        print("===============================")
        print(r.data)
        print('end of data r.data')
        try:
            response = api.request(r)
        except V20Error as e:
            print("V20Error: {}".format(e))
            return False, 0.0, 0
        else:
            print("Response: {}\n{}".format(r.status_code, json.dumps(response, indent=2)))
            try:
                return True, response['orderFillTransaction']['price'], response['orderFillTransaction']['id']
            except:
                # TODO Improve warning and errors syntax and exception treatment
                Warning('Order failed to execute. Likely not to have a descent available price.')
                return False, 0.0, 0
示例#15
0
def getPrice(ticker_type):

    accountID = "101-002-12644151-001"
    api = API(
        access_token=
        "1040f3b6997e1c6db66f7bb3bb8b5336-4ec7a67d82e48258fe56ac32c283eb12")
    params = {"instruments": ticker_type}
    print(ticker_type)
    r = pricing.PricingInfo(accountID=accountID, params=params)
    rv = api.request(r)

    data = pd.DataFrame(r.response["prices"])
    data_text = json.dumps(r.response, indent=2)
    ask = str(data["asks"])
    bid = str(data["bids"])
    #print(data_text) Update ** Allow it to be display different amount of digits properly
    bid_price = ""
    ask_price = ""
    for ch in range(4, len(ask)):
        if (ask[ch].isdigit() or ask[ch] == ".") and ch < 24:
            ask_price += ask[ch]
            bid_price += bid[ch]

    print("ASK:" + ask_price)
    print("BID:" + bid_price)
    print("#######################")
    return ask_price, bid_price
示例#16
0
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
示例#17
0
def history(instrument, window, collection=False):
    instrument = instrument
    data = list()
    client = API(token)
    params = {"count": 500, "granularity": window}
    r = InstrumentsCandles(instrument, params)
    client.request(r)
    resp = r.response
    for candle in resp.get('candles'):
        dt = candle['time']
        Open = candle['mid']['o']
        High = candle['mid']['h']
        Low = candle['mid']['l']
        Close = candle['mid']['c']
        Volume = candle['volume']
        update = [dt, Open, High, Low, Close, Volume]
        data.append(update)
    df = pd.DataFrame(data,
                      columns=['dt', 'Open', 'High', 'Low', 'Close', 'Volume'])
    # collect data, useful for research and weekends/holidays when the market isn't open
    if collection == True:
        title = 'data/%s_%s_history.csv' % (instrument, window)
        df.to_csv(title)

    return df
示例#18
0
    def __init__(self, instruments, granularity, prob_threshold, target,
                 account_name, *args, **kwargs):
        PricingStream.__init__(self, *args, **kwargs)
        print "loading model..."
        self.model = pickle.load(open('mpv12_0025_const.sav', 'rb'))
        self.instruments = instruments.split(',')
        self.target = target
        self.connected = False
        self.account_name = account_name
        self.granularity = granularity
        self.prob_threshold = prob_threshold
        self.status = {}
        for inst in self.instruments:
            self.status[inst] = {
                "bid": None,
                "ask": None,
                "time": None,
                "trade_pred": None,
                "current_pred": None,
                "long": 0,
                "short": 0,
                "unrealizedPL": 0,
                "pending_order": None,
                "made_prediction": False,
                "tradeID": None
            }

        print "connecting..."
        self.client = API(access_token=access_token, environment=environment)
示例#19
0
def get_historical_data_factory(instrument, params):
    # filename
    p_to = params['to'][:10]
    p_from = params['from'][:10]
    p_granularity = params['granularity']
    filename = f"data/data_oanda_{instrument}_{p_from}_{p_to}_{p_granularity}.csv"
    if os.path.isfile(filename):
        df2 = pd.read_csv(filename)
        df2['datetime'] = pd.to_datetime(df2['datetime'])
        df2 = df2.set_index('datetime')
        return df2

    # Create a Data Feed
    client = API(access_token=access_token)

    df_list = []

    def cnv(response):
        # for candle in response.get('candles'):
        #     print(candle)
        candles = [candle['mid'] for candle in response['candles']]

        ts = pd.DataFrame(
            {'datetime': [candle['time'] for candle in response['candles']]})

        vol = pd.DataFrame(
            {'volume': [candle['volume'] for candle in response['candles']]})

        candles_df = pd.DataFrame(data=candles)
        ts_df = pd.DataFrame(data=ts)
        vol_df = pd.DataFrame(data=vol)

        df = pd.concat([ts_df, candles_df, vol_df], axis=1)
        df.rename({
            'o': 'open',
            'h': 'high',
            'l': 'low',
            'c': 'close'
        },
                  axis=1,
                  inplace=True)

        df['datetime'] = pd.to_datetime(df['datetime'])
        df = df.set_index('datetime')
        for col in df.columns:
            df[col] = pd.to_numeric(df[col])
        df_list.append(df)

    for r in InstrumentsCandlesFactory(instrument=instrument, params=params):
        # print("FACTORY REQUEST: {} {} {}".format(r, r.__class__.__name__, r.params))
        rv = client.request(r)
        cnv(rv)

    df2 = pd.concat(df_list)
    now = datetime.datetime.now()
    dt_string = now.strftime("%Y%m%d%H%M%S")

    df2.to_csv(filename)

    return df2
示例#20
0
 def __init__(self):
     # OANDAアカウント読み込み
     self.oanda_account_id = os.environ.get("OANDA_API_ACCOUNT_ID")
     self.oanda_access_token = os.environ.get("OANDA_API_ACCESS_TOKEN")
     self.api = API(access_token=self.oanda_access_token,
                    environment="practice")
     self.date = ""
示例#21
0
class APIClient(object):
    def __init__(self, access_token, account_id, environment='practice'):
        self.access_token = access_token
        self.account_id = account_id
        self.client = API(access_token=access_token, environment=environment)

    def get_balance(self) -> Balance:
        req = accounts.AccountSummary(accountID=self.account_id)
        try:
            resp = self.client.request(req)
        except V20Error as e:
            logger.error(f'action=get_balance error={e}')
            raise

        available = float(resp['account']['balance'])
        currency = resp['account']['currency']
        return Balance(currency, available)

    def get_ticker(self, product_code) -> Ticker:
        params = {'instruments': product_code}
        req = PricingInfo(accountID=self.account_id, params=params)
        try:
            resp = self.client.request(req)
        except V20Error as e:
            logger.error(f'action=get_ticker error={e}')
            raise

        timestamp = datetime.timestamp(dateutil.parser.parse(resp['time']))
        price = resp['prices'][0]
        instrument = price['instrument']
        bid = float(price['bids'][0]['price'])
        ask = float(price['asks'][0]['price'])
        volume = 11111
        return Ticker(instrument, timestamp, bid, ask, volume)
示例#22
0
    def __init__(self, config, rpc):
        """
        Initializes this module with the given config,
        it does basic validation whether the specified
        exchange and pairs are valid.
        :return: None
        """
        self._conf.update(config)
        self.account_id, token = \
            self._conf["exchange"]["active_account"], \
            self._conf["exchange"]["token"]
        env = config.get("environment", "practice")
        self._api = API(access_token=token, environment=env)
        self.rpc = rpc

        self._cached_ticker: Dict[str, Any] = {}

        # Holds last candle refreshed time of each pair
        self._pairs_last_refresh_time: Dict[Tuple[str, str], int] = {}

        # Holds all open sell orders for dry_run
        self._dry_run_open_orders: Dict[str, Any] = {}

        if config['dry_run']:
            logger.info('Instance is running with dry_run enabled')

        logger.info('Using Exchange Oanda')

        self.markets = self.account_instruments()
        self.pairs = self.validate_pairs(config['exchange']['pair_whitelist'])
        self.order_book = self.oanda_order_book()
示例#23
0
def oanda_close_positions(side):
    # API取得
    api = API(access_token=token)

    # 注文内容
    if side == "BUY":
        order_data = {"shortUnits": "ALL"}
    if side == "SELL":
        order_data = {"longUnits": "ALL"}

    while True:
        # 注文実行
        try:
            r = positions.PositionClose(accountID,
                                        instrument=currency,
                                        data=order_data)
            api.request(r)
            print_log("\nすべての建玉を決済しました\n決済価格は平均 {}円です".format(
                str(data["forming"]["close_price"])))
            return order_data

        except V20Error as e:
            print_log("OANDAのAPIで問題発生" + str(e))
            print_log("20秒待機してやり直します")
            time.sleep(20)
示例#24
0
 def position_close_short(self, pair="AUD_USD", unit=1000):
     client = API(access_token=self.access_token, environment='live')
     ordr = PositionCloseRequest(shortUnits=unit)
     r = position.PositionClose(self.accountID,
                                instrument=pair,
                                data=ordr.data)
     rv = client.request(r)
    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()
示例#26
0
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
示例#27
0
def main():
    """
    My first attempt at pulling data from Oanda
    """

    oanda_environment = 'Practice'
    if oanda_environment == 'Live':
        # oanda_account_id = os.environ['OANDA_ACCOUNTID']
        oanda_access_token = os.environ['OANDA_ACCESS_TOKEN']
        # oanda_hostname = "api-fxtrade.oanda.com"
    else:
        # oanda_account_id = os.environ['OANDA_ACCOUNTID_DEV']
        oanda_access_token = os.environ['OANDA_ACCESS_TOKEN_DEV']
        # oanda_hostname = "api-fxpractice.oanda.com"
    # oanda_port = "443"

    client = API(oanda_access_token)
    instrument, granularity = "EUR_USD", "M15"
    _from = "2021-03-01T00:00:00Z"
    params = {"from": _from, "granularity": granularity}
    fn = "/tmp/{}.{}.json".format(instrument, granularity)
    if os.path.isfile(fn):
        os.remove(fn)
    with open(fn, "w") as OUT:
        # The factory returns a generator generating consecutive
        # requests to retrieve full history from date 'from' till 'to'
        json_data = list()
        for r in InstrumentsCandlesFactory(instrument=instrument,
                                           params=params):
            client.request(r)
            json_data.extend(r.response.get('candles'))
        OUT.write(json.dumps(json_data, indent=2))
示例#28
0
def test2():
    params = {"count": 10, "granularity": "D"}

    api = API(access_token=access_token, environment="practice")

    r = instruments.InstrumentsCandles(instrument="USD_JPY", params=params)

    rv = api.request(r)
    print(rv)

    p0 = rv['candles'][0]['mid']['c']
    p1 = rv['candles'][1]['mid']['c']
    p2 = rv['candles'][2]['mid']['c']
    p3 = rv['candles'][3]['mid']['c']
    p4 = rv['candles'][4]['mid']['c']
    p5 = rv['candles'][5]['mid']['c']
    p6 = rv['candles'][6]['mid']['c']
    p7 = rv['candles'][7]['mid']['c']
    p8 = rv['candles'][8]['mid']['c']
    p9 = rv['candles'][9]['mid']['c']

    print (p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)

    if p0 < p1:
        print ('↑')
    else:
        print ('↓')
示例#29
0
 def __init__(self, _from, _to, gran, instr):
     '''2017-01-01T00:00:00Z 2017-06-30T00:00:00Z H4 EUR_USD'''
     client = API(access_token=config['account']['token'])
     instrument = instr
     params = {"granularity": gran, "from": _from, "to": _to}
     for res in InstrumentsCandlesFactory(instrument=instr, params=params):
         self.rv = client.request(res)
示例#30
0
文件: arb_fx.py 项目: ganfxdd/docker
def oanda():
    account_id = ""
    access_token = ""

    api = API(access_token=access_token, environment="live")

    params = {"instruments": "USD_JPY"}
    pricing_info = PricingInfo(accountID=account_id, params=params)

    oal_ask = 0
    oal_ask_pre = 0
    oal_bid = 0
    oal_bid_pre = 0

    try:
        while True:
            api.request(pricing_info)
            response = pricing_info.response
            oal_ask_pre = oal_ask
            oal_ask = response['prices'][0]['asks']
            oal_bid_pre = oal_bid
            oal_bid = response['prices'][0]['bids']
            if oal_ask != oal_ask_pre:
                print("oandaask:" + str(oal_ask) + " oandabid:" + str(oal_bid))

    except V20Error as e:
        print("Error: {}".format(e))
示例#31
0
def test1():
    params ={"instruments": "EUR_USD,EUR_JPY"}

    # OANDAのデモ口座へのAPI接続
    api = API(access_token=access_token, environment="practice")

    r = pricing.PricingInfo(accountID=accountID, params=params)
    rv = api.request(r)

    print(rv['prices'][0]['bids'][0]['price'])
示例#32
0
 def setUp(self):
     """setup for all tests."""
     global access_token
     global accountID
     global account_cur
     global api
     # self.maxDiff = None
     try:
         accountID, account_cur, access_token = unittestsetup.auth()
         setattr(sys.modules["oandapyV20.oandapyV20"],
                 "TRADING_ENVIRONMENTS",
                 {"practice": {
                  "stream": "https://test.com",
                  "api": "https://test.com",
                  }})
         api = API(environment=environment, access_token=access_token)
         api.api_url = 'https://test.com'
     except Exception as e:
         print("%s" % e)
         exit(0)
示例#33
0
    def test__requests_exception(self):
        """force a requests exception."""
        from requests.exceptions import RequestException
        import oandapyV20.endpoints.accounts as accounts
        setattr(sys.modules["oandapyV20.oandapyV20"],
                "TRADING_ENVIRONMENTS",
                {"practice": {
                 "stream": "ttps://test.com",
                 "api": "ttps://test.com",
                 }})
        api = API(environment=environment,
                  access_token=access_token,
                  headers={"Content-Type": "application/json"})
        text = "No connection " \
               "adapters were found for 'ttps://test.com/v3/accounts'"
        r = accounts.AccountList()
        with self.assertRaises(RequestException) as oErr:
            api.request(r)

        self.assertEqual("{}".format(oErr.exception), text)