Ejemplo n.º 1
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)
Ejemplo n.º 2
0
def positionbook_plot_data_request(
    instrument: Union[str, None] = None, accountID: str = account
) -> Union[pd.DataFrame, bool]:
    """Request position 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]
        Position 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
    try:
        request = instruments.InstrumentsPositionBook(instrument=instrument)
        response = client.request(request)
        df_positionbook_data = pd.DataFrame.from_dict(
            response["positionBook"]["buckets"]
        )
        return df_positionbook_data
    except V20Error as e:
        d_error = json.loads(e.msg)
        print(d_error["errorMessage"], "\n")
        return False
Ejemplo n.º 3
0
def get_position_book(instrument, other_args):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="positionbook",
        description=
        "Plot the positionbook for the instrument if Oanda provides one.",
    )
    ns_parser = parse_known_args_and_warn(parser, other_args)
    if not ns_parser:
        return

    try:
        instrument = format_instrument(instrument, "_")
        request = instruments.InstrumentsPositionBook(instrument=instrument)
        response = client.request(request)
        df = pd.DataFrame.from_dict(response["positionBook"]["buckets"])
        pd.set_option("display.max_rows", None)
        df = df.take(range(219, 415, 1))
        book_plot(df, instrument, "Position Book")
        print("")

    except V20Error as e:
        # pylint: disable=W0123
        d_error = eval(e.msg)
        print(d_error["errorMessage"], "\n")
Ejemplo n.º 4
0
    def add_positionbook_data(self):

        r = instruments.InstrumentsPositionBook(instrument=self.symbol)
        self.df_positionbook = pd.DataFrame(self.api.request(r))

        path = '..\\..\\datastore\\_{0}\\{1}\\positionbook.pkl'.format(
            self.account_type, self.symbol)
        self.df_positionbook.to_pickle(path)
Ejemplo n.º 5
0
 def test__instruments_positionbook(self, mock_get):
     """get the positionbook information for instruments."""
     instrument = "EUR_USD"
     tid = "_v3_instruments_instrument_positionbook"
     resp, data, params = fetchTestData(responses, tid)
     r = instruments.InstrumentsPositionBook(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)
Ejemplo n.º 6
0
def main():
    config = Config()

    start = "2021-10-06 00:00:00"
    end = "2021-10-11 00:00:00"
    target_dts = pd.date_range(start=start, end=end, freq="5T").values

    for target_date in target_dts:
        params = {"time": target_date.astype(str)[:-7] + "Z"}
        print(target_date.astype(str)[:-7] + "Z")
        r = instruments.InstrumentsPositionBook(instrument="USD_JPY",
                                                params=params)
        _ = config.api.request(r)

        df = BookResponseFormatter().format(r.response)
        df.to_csv(f"positionbooks/{target_date}.csv", index=False)
        time.sleep(1)
Ejemplo n.º 7
0
 async def __get_position_book(self, instrument: str, date_time: datetime,
                               vicinity: bool):
     params = {"time": date_time.isoformat() + "Z"}
     r = instruments.InstrumentsPositionBook(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["positionBook"]["price"])
         resp["positionBook"][
             "buckets"] = self.__extract_book_buckets_vicinity_of_price(
                 resp["positionBook"]["buckets"], price, range_n)
         return resp["positionBook"]
Ejemplo n.º 8
0
    def getInstrumentsPositionBook(self, instrument, dt):

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

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

        self.__data = []
        for raw in ic.response[self.__PSI_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.__PSI_BOOK][self.__TIME]))
        cur_price = float(ic.response[self.__PSI_BOOK][self.__CUR_PRICE])
        bucket_width = float(ic.response[self.__PSI_BOOK][self.__BUCKET_WIDTH])

        print(df)
        print(bucket_width)

        print(time)
        print(cur_price)
        idx_th = bucket_width * self.__CUT_TH
        self.__psi_df = df[(df.index > cur_price - idx_th)
                           & (df.index < cur_price + idx_th)]
        self.__psi_curpri = cur_price
Ejemplo n.º 9
0
def get_position_book(pair, oanda_api=oanda_api, oanda_account=oanda_account):
    client = oandapyV20.API(access_token=oanda_api)
    params = {}
    r = instruments.InstrumentsPositionBook(instrument=pair)
    client.request(r)
    return r.response
Ejemplo n.º 10
0
 def instruments_position_book(self, instrument, params={}):
     endpoint = instruments.InstrumentsPositionBook(instrument, params)
     ob = self.send_request(endpoint)
     return ob["positionBook"]["buckets"]