Example #1
0
def orderbook_plot_data_request(
    instrument: Union[str, None] = None, accountID: str = account
) -> Union[pd.DataFrame, bool]:
    """Request order book data for plotting.

    Parameters
    ----------
    instrument : Union[str, None]
        The loaded currency pair, by default None
    accountID : str, optional
        Oanda account ID, by default cfg.OANDA_ACCOUNT

    Returns
    -------
    Union[pd.DataFrame, bool]
        Order book data or False
    """
    if accountID == "REPLACE_ME":
        print("Error: Oanda account credentials are required.")
        return False
    if instrument is None:
        print("Error: An instrument should be loaded before running this command.")
        return False
    parameters = {"bucketWidth": "1"}
    try:
        request = instruments.InstrumentsOrderBook(
            instrument=instrument, params=parameters
        )
        response = client.request(request)
        df_orderbook_data = pd.DataFrame.from_dict(response["orderBook"]["buckets"])
        return df_orderbook_data
    except V20Error as e:
        d_error = json.loads(e.msg)
        print(d_error["errorMessage"], "\n")
        return False
Example #2
0
def get_order_book(instrument, other_args):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="orderbook",
        description=
        "Plot the orderbook for the instrument if Oanda provides one.",
    )

    ns_parser = parse_known_args_and_warn(parser, other_args)
    if not ns_parser:
        return
    parameters = {"bucketWidth": "1"}
    try:
        instrument = format_instrument(instrument, "_")
        request = instruments.InstrumentsOrderBook(instrument=instrument,
                                                   params=parameters)
        response = client.request(request)
        df = pd.DataFrame.from_dict(response["orderBook"]["buckets"])
        pd.set_option("display.max_rows", None)
        df = df.take(range(527, 727, 1))
        book_plot(df, instrument, "Order Book")
        print("")

    except V20Error as e:
        # pylint: disable=W0123
        d_error = eval(e.msg)
        print(d_error["errorMessage"], "\n")
Example #3
0
    def add_orderbook_data(self):

        r = instruments.InstrumentsOrderBook(instrument=self.symbol)
        self.df_orderbook = pd.DataFrame(self.api.request(r))

        path = '..\\..\\datastore\\_{0}\\{1}\\orderbook.pkl'.format(
            self.account_type, self.symbol)
        self.df_orderbook.to_pickle(path)
Example #4
0
def get_orderbook(instrument, time):
    client = 'client=oandapyV20.API(access_token=env['client'])'
    client = oandapyV20.API(access_token=client)
    params = {'time': time, 'Accept-Datetime-Format': 'RFC3339'}
    r = instruments.InstrumentsOrderBook(instrument=instrument,
                                          params=params)
    a = client.request(r)
    #print(a)#(r.response)
    return a          
Example #5
0
 def test__instruments_orderbook(self, mock_get):
     """get the orderbook information for instruments."""
     instrument = "EUR_USD"
     tid = "_v3_instruments_instrument_orderbook"
     resp, data, params = fetchTestData(responses, tid)
     r = instruments.InstrumentsOrderBook(instrument=instrument,
                                          params=params)
     mock_get.register_uri('GET',
                           "{}/{}".format(api.api_url, r),
                           text=json.dumps(resp))
     result = api.request(r)
     self.assertTrue(result == resp)
Example #6
0
 async def __get_order_book(self, instrument: str, date_time: datetime,
                            vicinity: bool):
     params = {"time": date_time.isoformat() + "Z"}
     r = instruments.InstrumentsOrderBook(instrument, params)
     try:
         resp = self.__recursive_request(r)  # レスポンスが返却されるまで一時停止する
     except V20Error as err:
         http_status_not_found = 404
         if err.code == http_status_not_found:
             return None
         logging.error(err.msg)
         return None
     if vicinity:
         range_n = 25
         price = float(resp["orderBook"]["price"])
         resp["orderBook"][
             "buckets"] = self.__extract_book_buckets_vicinity_of_price(
                 resp["orderBook"]["buckets"], price, range_n)
     return resp["orderBook"]
Example #7
0
    def getInstrumentsOrderBook(self, instrument, dt):

        params = {
            "time": dt.strftime(self.__DT_FMT),
        }

        # APIへ過去データをリクエスト
        ic = instruments.InstrumentsOrderBook(instrument=instrument,
                                              params=params)
        self.__api.request(ic)

        self.__data = []
        for raw in ic.response[self.__ORD_BOOK][self.__BUCKETS]:
            self.__data.append([
                float(raw[self.__PRICE]),
                float(raw[self.__LONG]),
                float(raw[self.__SHORT])
            ])

        # リストからデータフレームへ変換
        df = pd.DataFrame(self.__data)
        df.columns = [self.__PRICE, self.__LONG, self.__SHORT]
        df = df.set_index(self.__PRICE).sort_index(ascending=False)
        # date型を整形する
        time = pd.to_datetime(
            self.__changeDateTimeFmt(
                ic.response[self.__ORD_BOOK][self.__TIME]))
        cur_price = float(ic.response[self.__ORD_BOOK][self.__CUR_PRICE])
        bucket_width = float(ic.response[self.__ORD_BOOK][self.__BUCKET_WIDTH])

        print(df)
        print(bucket_width)

        print(time)
        print(cur_price)
        idx_th = bucket_width * self.__CUT_TH
        self.__ord_df = df[(df.index > cur_price - idx_th)
                           & (df.index < cur_price + idx_th)]
        self.__ord_curpri = cur_price
import oandapyV20
import oandapyV20.endpoints.instruments as instruments
import configparser

config = configparser.ConfigParser()
config.read('./config/config_v20.ini')
accountID = config['oanda']['account_id']
access_token = config['oanda']['api_key']

client = oandapyV20.API(access_token=access_token)
"""
# r = instruments.InstrumentsOrderBook(instrument="EUR_USD", params=params) 
params are an optional request query parameters, check developer.oanda.com for details
"""
params = {
    # optional values
}

r = instruments.InstrumentsOrderBook(instrument="EUR_USD")
client.request(r)
Example #9
0
def get_orders_book(pair, oanda_api=oanda_api, oanda_account=oanda_account):
    client = oandapyV20.API(access_token=oanda_api)
    params = {}
    r = instruments.InstrumentsOrderBook(instrument=pair, params=params)
    client.request(r)
    return r.response
Example #10
0
 def instruments_order_book(self, instrument, params={}):
     endpoint = instruments.InstrumentsOrderBook(instrument, params)
     ob = self.send_request(endpoint)
     return ob["orderBook"]["buckets"]
Example #11
0
def InstrumentsOrderBook(access_token, instrument, params):  # check
    'Get orderbook data for a specified Instrument.'
    r = instruments.InstrumentsOrderBook(instrument=instrument, params=params)
    client = API(access_token=access_token)
    client.request(r)
    return readable_output(Munch(r.response)), Munch(r.response)