Exemplo n.º 1
0
def go_short():
    # TODO: refactor this
    params = {"instruments": u.pair}
    r = pricing.PricingInfo(accountID=u.accountID, params=params)
    client.request(r)
    price_list = r.response.get('prices', {})
    price_dict = price_list[0]
    bids = price_dict.get('bids')
    current_bids = bids[0]
    current_bid_price = float(current_bids.get('price'))

    take_profit = (current_bid_price-0.0050)  # equivalent to 50 pips
    # TODO: Adjust the above and below
    position = position_size()

    try:
        order_data = MarketOrderRequest(instrument=u.pair,
                                        units=-position,  # tp.Units(position).value
                                        takeProfitOnFill={
                                            "price": tp.PriceValue(take_profit).value
                                            },
                                        trailingStopLossOnFill={
                                            "distance": "0.00500"
                                            })

        r = orders.OrderCreate(u.accountID, data=order_data.data)
        client.request(r)
        sleep(5)
        trade()
    except Exception:
        print("Placing short order failed, check the logs.")
        logging.exception('Placing short order failed.')
def main(data):
    global time
    global df
    global sub_df
    global time_5m
    api = API(access_token=access_token, environment="practice")
    r = pricing.PricingInfo(accountID=accountID, params={'instruments': instruments})
    rv = api.request(r)
    price = float(rv['prices'][0]['bids'][0]['price'])
    now = rv['prices'][0]['time'][:19]
    tik_data.append([
        now,
        price
        ])
    sub_df.loc[now] = price
    print(sub_df)
    if (time < datetime.datetime.now() and datetime.datetime.now() < time+time_5m) :
        print('stream')
        stream(price)
    else:
        time = time+time_5m
        print('initial')
        append_df(price)
    print('last')
    # ax.clear()
    mpf.plot(df, type='candle', volume=True, figratio=(12,4))
    print('finish')
Exemplo n.º 3
0
def market_order(instrument, units, sl):
    """units can be positive or negative, stop loss (in pips) added/subtracted to price """
    params = {"instruments": instrument}
    account_id = "101-002-12759455-001"
    r = pricing.PricingInfo(accountID=account_id, params=params)
    rv = client.request(r)
    if units > 0:
        price = float(rv["prices"][0]["closeoutAsk"])
        st_ls = price - sl
    else:
        price = float(rv["prices"][0]["closeoutBid"])
        st_ls = price + sl

    data = {
        "order": {
            "price": "",
            "stopLossOnFill": {
                "timeInForce": "GTC",
                "price": str(st_ls)
            },
            "timeInForce": "FOK",
            "instrument": str(instrument),
            "units": str(units),
            "type": "MARKET",
            "positionFill": "DEFAULT"
        }
    }
    return data
Exemplo n.º 4
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
Exemplo n.º 5
0
    def stream_to_queue(self):
        client = None
        req = None
        try:
            client = oandapyV20.API(access_token=self.access_token)
            params = {'instruments': self.instruments}
            req = pricing.PricingInfo(accountID=self.account_id, params=params)
        except Exception as e:
            errmsg = 'Caught exception when connecting to stream\n' + str(e)
            rq.terminate(errmsg)

        res = client.request(req)
        with open("history_stream.txt", "a") as file:
            file.write("@streming\tinit on ready\n")
        while (True):
            if StreamingForexPrices.put_event.is_set():
                res = client.request(req)
                tick = res['prices'][0]
                instrument = tick['instrument']
                time = pd.Timestamp(tick['time'])
                bid = tick['bids'][0]['price']
                ask = tick['asks'][0]['price']
                tev = TickEvent(instrument, time, bid, ask)
                self.events.put(tev)
                self.clear_tick_event()
                with open("history_stream.txt", "a") as file:
                    file.write("--- put --->\n")
            with open("history_stream.txt", "a") as file:
                file.write("@Streaming\t{} {} (B:{}, A:{})\n".format(
                    tev.time, tev.instrument, tev.bid, tev.ask))
Exemplo n.º 6
0
def main():
    config = Config()

    params = {"instruments": "USD_JPY"}
    r = pricing.PricingInfo(accountID=config.ACCOUNT_ID, params=params)
    _ = config.api.request(r)
    print(r.response)
Exemplo n.º 7
0
def oanda_prices():
    """Request instrument prices from oanda."""

    with PRMS_Database() as db:
        instrument_names = db.get_db_instruments()
        # if prices don't exist in the database, reload them
        if not instrument_names:
            load_instruments()
            instrument_names = db.get_db_instruments()

    instrument_keys = list(instrument_names.keys())
    instrument_keys_sorted = ",".join(instrument_keys)  # A sorted string

    params_prices = {"instruments": instrument_keys_sorted}
    pricing_details = pricing.PricingInfo(accountID=accountID,
                                          params=params_prices)
    client.request(pricing_details)
    pricing_details = pricing_details.response
    pricing_details = pricing_details["prices"]

    list_prices = []

    for header in pricing_details:
        instrument = header["instrument"]
        name = instrument_names.get(instrument)
        bid_price = header["bids"][0]["price"]
        ask_price = header["asks"][0]["price"]
        list_prices.append([name, bid_price, ask_price])

    return list_prices
Exemplo n.º 8
0
def fx_price_request(
        accountID: str = account,
        instrument: Union[str, None] = None) -> Union[Dict[str, str], bool]:
    """Request price for a forex pair.

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

    Returns
    -------
    Union[Dict[str, str], bool]
        The currency pair price or False
    """
    if accountID == "REPLACE_ME":
        console.print("Error: Oanda account credentials are required.")
        return False
    if instrument is None:
        console.print(
            "Error: An instrument should be loaded before running this command."
        )
        return False
    try:
        parameters = {"instruments": instrument}
        request = pricing.PricingInfo(accountID=accountID, params=parameters)
        response = client.request(request)
        return response
    except V20Error as e:
        d_error = json.loads(e.msg)
        console.print(d_error["errorMessage"], "\n")
        return False
Exemplo n.º 9
0
 def get_rates(self):
     """
     return latest rate of the instrument
     """
     params = {"instruments": self.__instrument}
     x = (pricing.PricingInfo(self.__client.get_accountID(), params=params))
     return self.__client.get_clientAPI().request(x)
Exemplo n.º 10
0
    def thread(self):
        client = None
        req = None
        try:
            client = oandapyV20.API(access_token=self.access_token)
            params = {'instruments':self.instruments}
            req = pricing.PricingInfo(accountID=self.account_id, params=params)
        except Exception as e:
            errmsg = 'Caught exception when connecting to stream\n' + str(e)
            req.terminate(errmsg)

        res = client.request(req)
        self.start()
        try:
            while self.run:
                self.wait_until_start_is_called()
                time.sleep(self.tick_interval)
                res = client.request(req)
                tick = res['prices'][0]
                instrument = tick['instrument']
                self.time = pd.DatetimeIndex([pd.Timestamp(tick['time'])]).astype(np.int64)[0]//10**9
                bid  = float(tick['bids'][0]['price'])
                ask  = float(tick['asks'][0]['price'])
                print('tickServer response:{}'.format(bid))
                self.ticks.append(bid)
        except:
            print('@OANDATickServerThread : exception raised.')
            traceback.print_exc()
            self.fxevents.put(event_thread.EventContainer(name='exception', value=[]))
Exemplo n.º 11
0
 def oanda_market_hours(self, market):
     params={"instruments": market}
     request = pricing.PricingInfo(self.oanda_account_id, params=params)
     rv = self.oanda.request(request)['prices'][0]
     if rv['status'] == 'tradeable':
         return True
     else:
         return False
Exemplo n.º 12
0
def get_currency_info(ticker):
    """
	Simple request that returns data on the specified currency. 
	"""
    inParams = {"instruments": ticker}
    pricing_get = pricing.PricingInfo(accountID=accID, params=inParams)
    api.request(pricing_get)
    return pricing_get.response
Exemplo n.º 13
0
 def connect_to_stream(self):
     try:
         client = oandapyV20.API(access_token=self.access_token)
         params = {'instruments': self.instruments}
         req = pricing.PricingInfo(accountID=self.account_id, params=params)
         return req
     except Exception as e:
         errmsg = 'Caught exception when connecting to stream\n' + str(e)
         rq.terminate(errmsg)
Exemplo n.º 14
0
 def oanda_ticker(self, market):
     params={"instruments": market}
     request = pricing.PricingInfo(self.oanda_account_id, params=params)
     rv = self.oanda.request(request)['prices'][0]
     if rv['status'] == 'tradeable': 
         ticker = rv['closeoutBid']
         return Decimal(ticker)
     else: 
         return None 
Exemplo n.º 15
0
def price():
    params = {"instruments": "EUR_USD"}
    price = pricing.PricingInfo(accountID=accountid, params=params)
    api.request(price)
    response = price.response

    bid = response['prices'][0]['bids'][0]['price']
    ask = response['prices'][0]['asks'][0]['price']
    return bid, ask
Exemplo n.º 16
0
def getCurrentPrice(instrument):
    # Load config
    connection = Connection()
    accountID = connection.config['ACCOUNT_ID']
    
    # Request
    params = {"instruments": instrument}
    r = pricing.PricingInfo(accountID, params)
    return connection.API.request(r)
Exemplo n.º 17
0
def get_price(params):
    api = API(access_token=ACCESS_TOKEN)
    try:
        request = pricing.PricingInfo(accountID=ACCOUNT_ID, params=params)
        response = api.request(request)
    except Exception as err:
        print(f'Error: {err}')
        raise
    return response
Exemplo n.º 18
0
    def get_price(self, currency):
        params = {"instruments": currency}

        req = pricing.PricingInfo(accountID=self.account_id, params=params)
        response = self.oanda.request(req)

        ask_price = response["prices"][0]["asks"][0]["price"]
        bid_price = response["prices"][0]["bids"][0]["price"]
        return ask_price, bid_price
Exemplo n.º 19
0
 def getCurrPrice(self, instrument):
     r = pricing.PricingInfo(accountID=self.accountID, 
                             params={"instruments": instrument})
     rv = self.request(r)
     priced = rv["prices"][0]
     if instrument != priced["instrument"]:
         return -1,-1
     bid = priced["bids"][-1]["price"]
     ask = priced["asks"][-1]["price"]
     return float(bid), float(ask)
Exemplo n.º 20
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'])
Exemplo n.º 21
0
def GetPrices():
	params = {"instruments" : instrument}
	try:
		req = pricing.PricingInfo(accountID=account_id, params=params)
		res = api.request(req)
		priceTime = res['prices'][0]['time']
		asksPrice = res['prices'][0]['asks'][0]['price']
		bidsPrice = res['prices'][0]['bids'][0]['price']
	except Exception as e:
		print(e)
	return priceTime, asksPrice, bidsPrice
Exemplo n.º 22
0
 def test__pricing(self, mock_get):
     """get the pricing information for instruments."""
     uri = 'https://test.com/v3/accounts/{}/pricing'.format(accountID)
     resp = responses["_v3_accounts_accountID_pricing"]['response']
     text = json.dumps(resp)
     mock_get.register_uri('GET', uri, text=text)
     params = {"instruments": "EUR_USD,EUR_JPY"}
     r = pricing.PricingInfo(accountID, params=params)
     result = api.request(r)
     s_result = json.dumps(result)
     self.assertTrue("EUR_USD" in s_result and "EUR_JPY" in s_result)
def aktualna_cena_pre(
        par):  # najde akutalnu cenu pre dany menovy par, sluzi na TP a SL

    import oandapyV20.endpoints.pricing as pricing
    params = {"instruments": str(par)}
    data_filter = pricing.PricingInfo(
        accountID=accountID,
        params=params)  # specifies values to call from request
    req_prices = api.request(data_filter)  # calls request, fetches data
    fetched_data = data_filter.response  # assigns fetched data to variable actual price, not needed
    cena = fetched_data["prices"][0]["bids"][0]["price"]
    return float(cena)
Exemplo n.º 24
0
    def pricing_info(self, instruments):
        if type(instruments) == "list":
            _ins = ","
            _ins = _ins.join(instruments)

            params = {"instruments": _ins}
        else:
            params = {"instruments": instruments}

        endpoint = pricing.PricingInfo(self.account_id, params)
        p = self.send_request(endpoint)
        return p["prices"]
Exemplo n.º 25
0
 def test__pricing(self, mock_get):
     """get the pricing information for instruments."""
     tid = "_v3_accounts_accountID_pricing"
     resp, data, params = fetchTestData(responses, tid)
     r = pricing.PricingInfo(accountID, params=params)
     mock_get.register_uri('GET',
                           "{}/{}".format(api.api_url, r),
                           text=json.dumps(resp))
     result = api.request(r)
     instr = params["instruments"].split(",")
     self.assertTrue(result["prices"][0]["instrument"] == instr[0]
                     and result["prices"][1]["instrument"] == instr[1])
Exemplo n.º 26
0
 def get_current_price(self, ticker):
     client = oandapyV20.API(access_token=self.access_token)
     params = {"instruments": ticker}
     rp = pricing.PricingInfo(accountID=self.account_ID, params=params)
     rv = client.request(rp)
     rr = rp.response['prices'][0]
     price = {}
     price['ask'] = float(rr['asks'][0]['price'])
     price['bid'] = float(rr['bids'][0]['price'])
     # print('Current: instrument:  ' + rr.get('instrument')
     #      + ', closeoutAsk:  ' + rr.get('closeoutAsk') + ', closeoutBid:  ' + rr.get('closeoutBid')
     #      + ', time:  ' + rr.get('time'))
     return price
Exemplo n.º 27
0
def latest_prices(type):
    ##make a request to get the latest price of EUR to USD and save to database
    api_pricing = pricing.PricingInfo(accountID=oanda_count_id, params=params)
    api_pricing_request = oanda_api.request(api_pricing)
    new_price_record = Price()
    new_price_record.price = api_pricing.response["prices"][0]["bids"][0][
        "price"]
    new_price_record.save()
    ##get the maximum
    ##minimum and averge price of the last 100 prices
    latest_prices = Price.objects.all().order_by("-date")[:100]
    prices = []
    prices_and_dates = []
    max_price = 0
    min_price = 0
    avg_price = 0
    for count, price in enumerate(latest_prices):
        prices.append(price.price)
        shaded = False
        if count % 2 == 0:
            shaded = True
        prices_and_dates.append({
            "date":
            price.date.astimezone(tz).strftime('%Y-%m-%d %H:%M:%S'),
            "price":
            price.price,
            "count":
            count,
            "shaded":
            shaded
        })
    max_price = max(prices)
    min_price = min(prices)
    avg_price = mean(prices)
    # return the minimum, mximum and average of last 100 prices and the last 100 prices
    # average is rounded off to 4 decimal places
    if type == "non-json":
        response = {
            "min": min_price,
            "max": max_price,
            "avg": round(avg_price, 4),
            "table_data": prices_and_dates
        }
    else:
        response = JsonResponse({
            "min": min_price,
            "max": max_price,
            "avg": round(avg_price, 4),
            "table_data": prices_and_dates
        })
    return response
Exemplo n.º 28
0
 def is_instrument_halted(self, symbol):
     sleep_time = 1
     while True:
         try:
             request = pricing.PricingInfo(accountID=self.account_id, params={"instruments": symbol})
             self.oanda.request(request)
             tradeable = request.response["prices"][0]["tradeable"]
             break
         except Exception as e:
             time.sleep(sleep_time)
             sleep_time = sleep_time * 2
             if sleep_time > 60:
                 sleep_time = 1
     return tradeable
Exemplo n.º 29
0
def getPrice(currency):
    """
    An API request to get the current price at the given pair
    :param currency: Currency pair to get current price
    :return: A float of the current price
    """
    pair = currency[:3] + "_" + currency[
        3:]  # Format the currency pair by removing the '_'
    params = {"instruments": pair}
    r = pricing.PricingInfo(accountID=accountID, params=params)
    rv = api.request(r)  # Create the order request
    r = r.response["prices"][0]["asks"][0][
        'price']  # parse response from dictionary
    r = float(r)  # convert data to a float
    return r
Exemplo n.º 30
0
def getSpread(currency):
    """
    Gets the spread of the given pair
    :param currency: Currency to get the spread of
    :return: A float that represents the difference between the buy and sell prices
    """
    pair = currency[:3] + "_" + currency[
        3:]  # Format the currency pair by removing the '_'
    params = {"instruments": pair}
    r = pricing.PricingInfo(accountID=accountID, params=params)
    rv = api.request(r)  # Create the order request
    sell = r.response['prices'][0]['bids'][0][
        'price']  # parse response from dictionary
    buy = r.response['prices'][0]['asks'][0]['price']
    spread = float(buy) - float(sell)
    return spread