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
Esempio n. 2
0
    def stream(self):
        """
        Description of Raw Stream:
        type ('PRICE'/'HEARTBEAT')
            time (str - 2017-11-01T10:29:20.628235935Z)
            bids
                price (float - 1.16365)
                liquidity (int - 10000000)
            asks
                price (float - 1.16365)
                liquidity (int - 10000000)
            closeoutBid
                price (float - 1.16365)
            closeoutAsk
                price (float - 1.16365)
            status (str - 'tradeable')
            tradeable (boolean - True)
            instrument (str - 'GBP_USD')

        :param input_financial_instrument: List of Financial Instruments (up to 20)
        :return: connection that stream prices
        """
        conn = Oanda()

        input_financial_instrument = self.currencies

        financial_instrument = input_financial_instrument[0]
        for security in input_financial_instrument[1:]:
            financial_instrument += "," + security

        params = {"instruments": financial_instrument}
        conn_params = pricing.PricingStream(accountID=conn.account_id, params=params)
        return conn.api.request(conn_params)
Esempio n. 3
0
 def start(self, **params):
     r = pricing.PricingStream(self.account_id, params)
     rv = self.client.request(r)
     for tick in rv:
         if (tick['type'] != 'HEARTBEAT'):
             print(tick)
             self.on_success(tick)
Esempio n. 4
0
    def run(self):
        cf = PRecordFactory(self.pt.granularity)
        r = pricing.PricingStream(accountID=self.accountID,
                                  params={"instruments": self.pt.instrument})
        for tick in self.client.request(r):
            rec = cf.parseTick(tick)
            if rec:
                self.pt.addItem(*rec)

            self._botstate()
Esempio n. 5
0
def event_new_tick(instrument):
    """
	returns true if a new bar has formed since the last interval check. 
	"""
    inParam = {"instruments": instrument}

    price_stream = pricing.PricingStream(accountID=accID, params=inParam)
    client.request(price_stream)

    return price_stream.response
Esempio n. 6
0
def PricingPricingStream(access_token, accountID, params=None):  # check
    'Get realtime pricing information for a specified list of Instruments.'
    # terminate(message='') to terminate
    r = pricing.PricingStream(accountID=accountID, params=params)
    client = API(access_token=access_token)
    client.request(r)
    maxrecs = 100
    for ticks in r.response:
        print(dumps(ticks, indent=4, separators=(',', ': ')))
        if maxrecs == 0:
            r.terminate("maxrecs records received")
 def _live_data(self, instrument='EUR_USD'):
     """
     Subscribes to the stream of data of an instrument.
     """
     s = pricing.PricingStream(accountID=self.accountID, 
                               params={"instruments": instrument})
     try:
         for resp in self.client.request(s):
             self.filter_data(resp)
     
     except V20Error as e:
         print("Error: {}".format(e))
Esempio n. 8
0
    def streaming_price(self, callback):
        p = {"instruments": "USD_JPY"}
        r = pricing.PricingStream(self.id, params=p)

        api = oandapyV20.API(self.token)
        rv = self.client.request(r)

        for ticks in rv:
            price = self._streaming_price_bits_asks(ticks)
            if price is not None:
                price['time'] = price['time'].split('.')[0]
                price['time'] = price['time'].replace('T', ' ')
                print(price['time'])

                callback(datetime.strptime(price['time'], '%Y-%m-%d %H:%M:%S'),
                         float(price['bids']), float(price['asks']))
Esempio n. 9
0
    def __init__(self, init_invest=1000):

        file = open("access.txt", "r+")
        self.access_token = '82957cd1a8234cf899f729284c094d27-e31e01c267351992774813f5e64c8b43'  #file.readline()
        self.accountID = "101-004-12401398-001"  #file.readline()
        print(self.accountID)
        print(self.access_token)
        file.close()
        self.init_invest = init_invest  #initial balance
        self.client = oandapyV20.API(access_token=self.access_token)
        self.r = accounts.AccountDetails(
            self.accountID)  #requests (about out account)
        params = {"instruments": "EUR_USD", "timeout": "5"}
        self.pc = pricing.PricingStream(self.accountID,
                                        params)  #stream of prices
        self.order_type = 'market'
        self.tickcounter = 0
        #self.init_balance_diff = 0

        #self.cur_step = None
        self.stock_owned = None
        self.balance = None  #== position value
        self.bid_close = None
        self.ask_close = None
        self.bid_close_p1 = None
        self.ask_close_p1 = None

        # action space
        self.action_space = spaces.Discrete(3)

        # observation space: give estimates in order to sample and build scaler
        balance_range = np.array((-init_invest * 2, init_invest * 2))
        stock_range = np.array((0, init_invest * 2 // 1.5))  #stock owned
        bid_range = np.array((0, 1.5))
        ask_range = np.array((0, 1.5))
        ask_p1_range = ask_range
        bid_p1_range = bid_range

        self.observation_space = spaces.Box(
            low=np.array((balance_range[0], stock_range[0], bid_range[0],
                          ask_range[0], ask_p1_range[0], bid_p1_range[0])),
            high=np.array((balance_range[1], stock_range[1], bid_range[1],
                           ask_range[1], ask_p1_range[1], bid_p1_range[1])))

        self._reset()
Esempio n. 10
0
    def get_tickstream(self, instruments_list):
        r = pricing.PricingStream(
            accountID=accountID,
            params={"instruments": ",".join(instruments_list)})

        n = 0
        stopAfter = 2  # let's terminate after receiving 3 ticks
        try:
            # the stream requests returns a generator so we can do ...
            for tick in self.client.request(r):
                print json.dumps(tick, indent=2)
                if n >= stopAfter:
                    r.terminate()
                n += 1

        except StreamTerminated as err:
            print(
                "Stream processing ended because we made it stop after {} ticks"
                .format(n))
Esempio n. 11
0
def price_stream(pairs, currencies, bd):
    '''
    Request a price stream from oanda for every instrument in pairs.
    With every updated price, update currency prices
    Store values in db. not figured out how yet)
    '''
    global pairs_bid
    global pairs_ask
    global universe
    
    
    # Stream Parameters
    pairs_list = ','.join(pairs)
    account='101-001-7518331-001'
    client = 'f01b219340f61ffa887944e7673d85a5-'
    client += '6bcb8a840148b5c366e17285c984799e'
    api = oandapyV20.API(access_token=client)
    params ={'instruments': pairs_list} 
    r = pricing.PricingStream(accountID=account, params=params)
    
    # Begin Stream
    rv = api.request(r)
    for ticks in rv:
        if ticks['type'] == 'PRICE':
            mid = (float(ticks['asks'][0]['price']) \
                + float(ticks['bids'][0]['price'])) / 2
            pairs_mid[ticks['instrument']] = mid
            pairs_mid['timestamp'] = ticks['time']
            universe['timestamp'] = ticks['time']
            
            # Reduce for streaming insertion
            stream = {'timestamp': ticks['time'],
                      'instrument': ticks['instrument'],
                      'ask': ticks['asks'][0]['price'],
                      'bid': ticks['bids'][0]['price']}
            
            # Calculate Currencies
            calculate_currencies(pairs, currencies, pairs_mid)
            
            # Insert instrument an duniverse pricing into db
            db_insert(db, 'universe', universe)
            db_insert(db, 'instruments', pairs_mid)
            db_insert(db, 'stream', stream)            
Esempio n. 12
0
    def test__pricing_stream(self, mock_get):
        """get the streaming pricing information for instruments."""
        tid = "_v3_accounts_accountID_pricing_stream"
        resp, data, params = fetchTestData(responses, tid)
        text = "\n".join([json.dumps(t) for t in resp])
        r = pricing.PricingStream(accountID, params=params)
        mock_get.register_uri('GET', "{}/{}".format(api.api_url, r), text=text)
        result = []
        n = 0
        m = 3
        with self.assertRaises(StreamTerminated):
            for rec in api.request(r):
                result.append(rec)
                n += 1
                # terminate when we have m response lines
                if n == m:
                    r.terminate()

        # the result containing m items, should equal the first m items
        self.assertTrue(result == resp[0:m])
Esempio n. 13
0
def AlgoTrader():
    #api = API(access_token="77e52f20c91e859b1edbf6f63a049994-0d58a82089e68f5437225b0daffbad96")
    #accountID = "101-001-7189583-001"
    api = API(
        access_token=
        "280131fad16391b7433e29967e7fb384-9b1ad7bee86ec27e2d9234147accbea3")
    accountID = "101-011-7185005-001"

    config = configparser.ConfigParser()  # 3
    config.read('oanda.cfg')  # 4

    mt = MyTrader(momentum=12,
                  environment='practice',
                  access_token=config['oanda']['access_token'])

    params = {"instruments": "AUD_CAD"}
    r = pricing.PricingStream(accountID=accountID, params=params)
    #rv = api.request(r)
    maxrecs = 100

    #mt.rates(account_id=config['oanda']['account_id'],
    #        instruments=['DE30_EUR'], ignore_heartbeat=True)
    dict_o = {}
    dict_i = {}
    ignore_heartbeat = True
    for i in range(250):
        #print(i)
        rv = api.request(r)
        for line in rv:
            dict_o.clear()
            dict_i.clear()
            dict_i['ask'] = float(line['closeoutAsk'])
            dict_i['bid'] = float(line['closeoutBid'])
            dict_i['instrument'] = line['instrument']
            dict_i['time'] = line['time']
            dict_o['tick'] = dict_i
            #data = json.loads(line.decode("utf-8"))
            mt.on_success(json.loads(json.dumps(dict_o)))
            break
    print("end")
    def run(self):
        def append_record(record):
            with open(
                    '/media/office/0D82-9628/data/tick_data/tick_file_7.json',
                    'a', os.O_NONBLOCK) as f:
                json.dump(record, f)
                f.write(os.linesep)

        # to retrieve:
        # with open('my_file') as f:
        #     my_list = [json.loads(line) for line in f]

        index = 1
        cf = PRecordFactory(self.pt.granularity)
        r = pricing.PricingStream(accountID=self.accountID,
                                  params={"instruments": self.pt.instrument})
        for tick in self.client.request(r):
            # print(sys._getframe().f_lineno)
            # print('tick ', tick)
            # np.save('./tick_data/tick_' + str(index) + '.npy', tick)
            # index += 1

            if 'PRICE' in tick['type']:
                # print(tick.keys())
                print(tick)
                append_record(tick)
                # tick = np.load('oanda_tick.npy')
                rec = cf.parseTick(tick)
                # print('rec after parseTick ', rec)
                # exit()
            # exit()

            # if rec:
            # print(sys._getframe().f_lineno)
            # print('rec after if ', rec)
            # exit()
            # self.pt.addItem(*rec)

            self._botstate()
Esempio n. 15
0
def price_stream(currency_pairs):    
    # Just a little titillation (can pass shit along based on, you know, stuff)
    def go():
        print('YES')
        print()
        return
    # Main Body
    account='101-001-7518331-001'
    client = 'client=oandapyV20.API(access_token=env['client'])'
    api = oandapyV20.API(access_token=client)
    params ={'instruments': 'EUR_USD, EUR_JPY'}
    params ={'instruments': currency_pairs}
    r = pricing.PricingStream(accountID=account, params=params)
    rv = api.request(r)
    maxrecs = 10
    for ticks in rv:
        if ticks['type'] == 'PRICE':
            print(json.dumps(ticks['instrument'], indent=4),",")
            print(json.dumps(ticks['asks'][0]['price'], indent=4),",")
            if float(ticks['asks'][0]['price']) < 1000:
                go()
            if maxrecs == 0:
                r.terminate("maxrecs records received")
Esempio n. 16
0
    def test__pricing_stream(self, mock_get):
        """get the streaming pricing information for instruments."""
        uri = 'https://test.com/v3/accounts/{}/pricing/stream'.format(
            accountID)
        ticks = [{"a": 10}, {"b": 20}, {"c": 30}, {"d": 40}, {"e": 50}]
        text = "\n".join([json.dumps(r) for r in ticks])
        mock_get.register_uri('GET', uri, text=text)
        params = {"instruments": "EUR_USD,EUR_JPY"}
        r = pricing.PricingStream(accountID, params=params)
        result = []
        n = 0
        with self.assertRaises(StreamTerminated) as oErr:
            for rec in api.request(r):
                result.append(json.dumps(rec))
                n += 1
                # terminate when we have 3 response lines
                if n == 3:
                    r.terminate()

        # the result containing 3 items, should equal the first 3 items
        # of the ticks
        self.assertTrue("\n".join(result) == "\n".join(
            json.dumps(r) for r in ticks[0:3]))
Esempio n. 17
0
def pricing_stream(accountID, token, instruments):
    params = create_parameters(instruments)
    client = oandapyV20.API(access_token=token)
    r = pricing.PricingStream(accountID=accountID, params=params)
    request = client.request(r)
    return request
Esempio n. 18
0
 def updatePosLog(self, broker, accountID):
     if broker == 'oanda':
         oT = dict(cfg.brokerList['oanda']['accounts'][accountID]
                   ['tsv'].__next__())
         print(oT)
         if oT["type"] == "ORDER_FILL":
             if "tradeOpened" in oT.keys():
                 oC = oT["tradeOpened"]
                 tempL = [
                     o for o in cfg.posList if o.posID == oC["tradeID"]
                 ]
                 if tempL == []:
                     if not oT["instrument"] in cfg.pairList:
                         cfg.pairList.append(oT["instrument"])
                         cfg.pairList.sort()
                         client = oandapyV20.API(
                             access_token=cfg.brokerList['oanda']['token'])
                         parstreamtrans = \
                             {
                                 "instruments": ",".join(cfg.pairList)
                             }
                         pstream = pricing.PricingStream(
                             accountID=cfg.brokerList['oanda']['accounts']
                             [accountID]['ID'],
                             params=parstreamtrans)
                         cfg.brokerList[broker]['psv'] = client.request(
                             pstream)
                     if float(oC["units"]) >= 0:
                         typePos = 'l'
                     else:
                         typePos = 's'
                     cfg.posList.append(
                         Position('oanda', accountID, oC["tradeID"],
                                  oT["instrument"], float(oT["price"]),
                                  abs(float(oC["units"])), typePos,
                                  pd.Timestamp(oT["time"])))
                     cfg.posList[-1].status = 'o'
                     cfg.brokerList['oanda']['accounts'][accountID][
                         'log'].loc[pd.Timestamp(oT["time"])] = float(
                             oT["accountBalance"])
             if "tradesClosed" in oT.keys():
                 oCl = oT["tradesClosed"]
                 oCl.reverse()
                 for ocp in oCl:
                     iL = [
                         j for j in range(cfg.posList.__len__())
                         if cfg.posList[j].account == accountID
                         and cfg.posList[j].posID == ocp["tradeID"]
                     ]
                     i = int(iL[0])
                     v = cfg.posList[i].log.iloc[-1, ].vol - abs(
                         float(ocp["units"]))
                     p = oT["price"]
                     cp = float(ocp["realizedPL"])
                     comm = float(oT["commission"]) / oCl.__len__()
                     t = pd.Timestamp(oT["time"])
                     cfg.posList[i].log.loc[t] = {
                         'vol': v,
                         'price': p,
                         'closedprof': cp,
                         'commission': comm
                     }
                     if cfg.posList[i].log.loc[t].vol == 0:
                         cfg.posList[i].status = 'c'
                     cfg.brokerList['oanda']['accounts'][accountID][
                         'log'].loc[t] = float(oT["accountBalance"])
             if "tradeReduced" in oT.keys():
                 oRe = oT["tradeReduced"]
                 iL = [
                     j for j in range(cfg.posList.__len__())
                     if cfg.posList[j].account == accountID
                     and cfg.posList[j].posID == oRe["tradeID"]
                 ]
                 i = int(iL[0])
                 v = cfg.posList[i].log.iloc[-1, ].vol - abs(
                     float(oRe["units"]))
                 p = oT["price"]
                 cp = float(oT["tradeReduced"]["realizedPL"])
                 comm = float(oT["commission"])
                 t = pd.Timestamp(oT["time"])
                 cfg.posList[i].log.loc[t] = {
                     'vol': v,
                     'price': p,
                     'closedprof': cp,
                     'commission': comm
                 }
                 if cfg.posList[i].log.loc[t].vol == 0:
                     cfg.posList[i].status = 'c'
                 cfg.brokerList['oanda']['accounts'][accountID]['log'].loc[
                     t] = float(oT["accountBalance"])
Esempio n. 19
0
    def trading(self, broker):

        try:

            if broker == 'Forexcom':

                self.ls_client = LightstreamerClient(
                    self.broker1.username, self.broker1.session_id,
                    "https://push.cityindex.com", "STREAMINGALL")

                try:
                    self.ls_client.connect()
                except Exception as e:
                    print("Unable to connect to Lightstreamer Server", e)

                subscription = LightstreamerSubscription(
                    adapter="PRICES",
                    mode="MERGE",
                    items=["PRICE." + str(self.broker1.market_id)],
                    fields=["Bid", "Offer"])
                subscription.addlistener(self.quotesHandler)

                self.ls_client.subscribe(subscription)

                while True:
                    if self.run == False:
                        self.ls_client.disconnect()
                        return None

            elif broker == 'Oanda':

                params = {
                    "instruments": self.broker2.ccy,
                }

                req = pricing.PricingStream(accountID=self.broker2.account_id,
                                            params=params)
                resp_stream = self.broker2.client.request(req)
                for ticks in resp_stream:
                    if self.run == True:

                        if ticks['type'] != 'HEARTBEAT':

                            self.last_quote2['bid'] = float(
                                ticks['bids'][0]['price'])
                            self.last_quote2['ask'] = float(
                                ticks['asks'][0]['price'])
                            self.time_stamp2 = datetime.datetime.now()
                            if self.time_stamp2.hour == TRD_RESET_HOUR:  #reset daily trade limit
                                self.trd_time = 0

                            if (self.time_stamp2-self.trd_buffer_time).total_seconds()>self.trd_buffer and \
                                    (self.time_stamp2-self.safe_buffer_time).total_seconds()>self.safe_buffer: #only call execute when resume==True
                                self.locker.acquire()
                                self.execute()
                                self.locker.release()

                            self.stream_queue.put(broker + '(' + self.ccy +
                                                  ')' + ' ' +
                                                  self.time_stamp2.strftime(
                                                      "%Y-%m-%d %H:%M:%S") +
                                                  ' ' + str(self.last_quote2))
                    else:
                        return None

            else:

                print('unknwon broker...')
                return None

        except Exception as error:

            try:
                self.locker.release()
            except Exception as lckErr:
                None

            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
            if broker == 'Forexcom':
                self.ls_client.disconnect()  #disconnect first
                self.broker1.connect()
            elif broker == 'Oanda':
                self.broker2.connect()

            print(
                str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +
                ' ' + broker + ' trading failed: ' + str(error))
            print('restarting ' + broker + ' ...')
            time.sleep(30)
            self.trading(broker)
Esempio n. 20
0
from oandapyV20.exceptions import V20Error


accountID = '101-001-1407695-002' 
access_token = 'f9263a6387fee52f94817d6cd8dca978-d097b210677ab84fb58b4655a33eb25c'


client = oandapyV20.API(access_token=access_token, environment="practice")

mktOrder = MarketOrderRequest(instrument="EUR_USD",
                              units=10000,
                              takeProfitOnFill=TakeProfitDetails(price=1.10).data,
                              stopLossOnFill=StopLossDetails(price=1.07).data
                              ).data
r = orders.OrderCreate(accountID=accountID, data=mktOrder)
client.request(r)

instruments = ["EUR_USD", "EUR_JPY"]
s = pricing.PricingStream(accountID=accountID, params={"instruments": ",".join(instruments)})
try:
    n = 0
    for R in client.request(s):
        print(json.dumps(R, indent=2))
        n += 1
        if n > 10:
            s.terminate("maxrecs received: {}".format(10))

except V20Error as e:
    print("Error: {}".format(e))
    
Esempio n. 21
0
 def test__pricing_stream_termination_1(self):
     """terminate a stream that does not exist."""
     params = {"instruments": "EUR_USD,EUR_JPY"}
     r = pricing.PricingStream(accountID, params=params)
     with self.assertRaises(ValueError):
         r.terminate()
Esempio n. 22
0
            },
            "stopLoss": {
                "timeInForce": "GTC",
                "price": X.next()
            }
        }
        r = trades.TradeCRCDO(accountID, tradeID=O, data=cfg)
        rv = api.request(r)
        print("RESP:\n{} ".format(json.dumps(rv, indent=2)))

if chc == 'streamprice':
    params =\
        {
            "instruments": "EUR_USD,EUR_JPY"
        }
    r = pricing.PricingStream(accountID=accountID, params=params)
    rv = api.request(r)
    maxrecs = 1000
    for ticks in rv:
        maxrecs -= 1
        print(json.dumps(ticks, indent=4), ",")
        if maxrecs == 0:
            # r.terminate("maxrecs records received")
            break

if chc == 'streamtrans':
    params = {"instruments": "EUR_USD,EUR_JPY"}
    r = trans.TransactionsStream(accountID=accountID)
    rv = api.request(r)
    maxrecs = 5
    try:
Esempio n. 23
0
 def open(self, broker, accountID, typeP, pair, vol, price,
          slip):  # Falta log
     try:
         if broker == "backtest":
             cfg.posList.append(
                 Position(
                     'backtest', accountID, str(accountID), pair, price,
                     vol, typeP, cfg.priceList['backtest']['accounts']
                     [accountID].ts.max()))
             cfg.posList[-1].status = 'o'
             if pair[-3:] == cfg.brokerList[broker]['accounts'][accountID][
                     'curr']:
                 conv = 1
             elif ('_').join([pair[-3:], cfg.brokerList[broker]['accounts'][accountID]['curr']]) in \
                     cfg.priceList[broker]['accounts'][accountID].index:
                 conv = cfg.priceList[broker]['accounts'][accountID].bid[(
                     '_'
                 ).join([
                     pair[-3:],
                     cfg.brokerList[broker]['accounts'][accountID]['curr']
                 ])]
             elif ('_').join([cfg.brokerList[broker]['accounts'][accountID]['curr'], pair[-3:]]) in \
                     cfg.priceList[broker]['accounts'][accountID].index:
                 conv = cfg.priceList[broker]['accounts'][accountID].ask[(
                     '_'
                 ).join([
                     cfg.brokerList[broker]['accounts'][accountID]['curr'],
                     pair[-3:]
                 ])]**(-1)
             bal = cfg.brokerList['backtest']['accounts'][accountID][
                 'log'].iloc[-1, ].balance - price * vol * conv
             nav = bal + pd.Series(
                 [po.tick()
                  for po in cfg.posList if po.status == 'o']).sum()
             cfg.brokerList['backtest']['accounts'][accountID]['log'].loc[
                 cfg.priceList['backtest']['accounts']
                 [accountID].ts.max()] = {
                     'balance': bal,
                     'NAV': nav
                 }
         if broker == "oanda":
             client = oandapyV20.API(
                 access_token=cfg.brokerList['oanda']['token'])
             if typeP == 'l':
                 sign = 1
                 priceB = (1 + slip) * price
             if typeP == 's':
                 sign = -1
                 priceB = (1 - slip) * price
             data = \
                 {
                     "order": {
                         "units": str(sign * vol),
                         "instrument": pair,
                         "timeInForce": "FOK",
                         "type": "MARKET",
                         "positionFill": "OPEN_ONLY",
                         "priceBound": str(round(priceB, 5))
                     }
                 }
             r = orders.OrderCreate(
                 cfg.brokerList['oanda']['accounts'][accountID]['ID'],
                 data=data)
             ro = dict(client.request(r))
             if "orderFillTransaction" in ro.keys():
                 oT = ro["orderFillTransaction"]
                 if "tradeOpened" in oT.keys():
                     oC = oT["tradeOpened"]
                     tempL = [
                         o for o in cfg.posList if o.posID == oC["tradeID"]
                     ]
                     if tempL == []:
                         if not oT["instrument"] in cfg.pairList:
                             cfg.pairList.append(oT["instrument"])
                             cfg.pairList.sort()
                             client = oandapyV20.API(
                                 access_token=cfg.brokerList['oanda']
                                 ['token'])
                             parstreamtrans = \
                                 {
                                     "instruments": ",".join(cfg.pairList)
                                 }
                             pstream = pricing.PricingStream(
                                 accountID=cfg.brokerList['oanda']
                                 ['accounts'][accountID]['ID'],
                                 params=parstreamtrans)
                             cfg.brokerList[broker]['psv'] = client.request(
                                 pstream)
                         if float(oC["units"]) >= 0:
                             typePos = 'l'
                         else:
                             typePos = 's'
                         cfg.posList.append(
                             Position('oanda', accountID, oC["tradeID"],
                                      oT["instrument"], float(oT["price"]),
                                      abs(float(oC["units"])), typePos,
                                      pd.Timestamp(oT["time"])))
                         cfg.posList[-1].status = 'o'
                         cfg.brokerList['oanda']['accounts'][accountID][
                             'log'].loc[pd.Timestamp(oT["time"])] = float(
                                 oT["accountBalance"])
     finally:
         pass
Esempio n. 24
0
#############
'''
trade_size = 1000000  # Update this
instrument = 'AUD_CAD'  # Update this
short_ticks = 5
long_ticks = 10
tick_number = 0
mid_price_list = []
initial_balance = get_nav(client, account_id)
'''
###############
# TRADING BOT #
###############
'''
# Initialises data stream
stream = pricing.PricingStream(accountID=account_id,
                               params={"instruments": instrument})
stream_request = api.request(stream)

# TODO Create function within function for printing all 3 lines of NAV
# TODO DO ABOVE and then add PNL as percentage as well as $$$$$
# TODO format (all) numbers (NAV/PNL)

# TODO do everything in a DataFrame and RESAMPLE to 10 seconds

# TODO CREATE A CLASS that includes functions that are together
# Trading bot
for tick in stream.response:
    tick_data = json.dumps(tick)  # Dict to string
    tick_data = json.loads(tick_data)  # String to JSON
    print("----------------")
Esempio n. 25
0
def price_stream(
        pairs_index,
        db,
        bids_or_asks,
        q1,  #q2, q3, q4, q5,
        oanda_api=oanda_api,
        oanda_account=oanda_account):
    """
    Stream Prices from Oanda for pairs list.  Insert into 'pairs' table
    Load data into a q if passed as argument
    """
    # Create Pairs Dictionary
    pairs_dictionary = dict(zip(pairs_index, [1] * len(pairs_index)))
    pairs_dictionary['timestamp'] = str(np.datetime64('now'))

    # Create Database
    statement = 'create table if not exists pairs (' \
                'id integer primary key, timestamp text not null, '
    statement += ' real not null, '.join(pairs_index)
    statement += ' real not null);'
    database_execute(db, statement)
    database_execute(db, 'delete from pairs')

    # Streaming Parameters
    api = oandapyV20.API(
        access_token=
        'f3e81960f4aa75e7e3da1f670df51fae-73d8ac6fb611eb976731c859e2517a9b')
    params = {'instruments': ','.join(pairs_index)}
    r = pricing.PricingStream(accountID=oanda_account, params=params)
    print('Streaming Oanda Pricing Data:')

    # Start Data Stream
    count = 1
    while True:
        try:
            for ticks in api.request(r):
                if ticks['type'] == 'PRICE':
                    if ticks['instrument'] in pairs_index:

                        # Update Pairs Dictionary with price and time
                        price = float(ticks[bids_or_asks][0]['price'])
                        pairs_dictionary[ticks['instrument']] = price
                        pairs_dictionary['timestamp'] = ticks['time']

                        # Insert pairs Dictionary into pairs table
                        dictionary_insert(db, 'pairs', pairs_dictionary)

                        # Load row into q and update count
                        q1.put(count)
                        # q2.put(count)
                        # q3.put(count)
                        # q4.put(count)
                        # q5.put(count)

                        count += 1
                        # Debug - testing timestamps
                        if count % 500 == 0:
                            print('Sent {}:        {}'.format(
                                count, ticks['time']))
                            print('Queued {}:      {}'.format(
                                count, (str(datetime.datetime.now()))))

        except Exception as e:
            print(e)
Esempio n. 26
0
 def build_stream(self):
     return pricing.PricingStream(accountID=self.client.account, params={'instruments': self.instruments} )