def __init__(self, account_id, access_token, environment='practice'): DataConnection.__init__(self) import oandapy # pylint: disable=import-error self.account_id = account_id self.environment = environment self.oanda = oandapy.API(environment=environment, access_token=access_token)
def check_order(self,check): if check== True: oanda0 = oandapy.API(environment="practice", access_token=self.access_token) try: responseTrades = oanda0.get_trades(self.account_id,instrument=self.pairs) except Exception as e: logging.warning('Caught exception in get_trades() of check_order()!\n'+str(time.ctime())) return if responseTrades.get("trades")==[]: pd = self.pairs_dict pd["orlis"].pop(0) logging.info(" orlis: "+str(pd["orlis"])) pd["orlis"].append(0) logging.info(" orlis: "+str(pd["orlis"])) if pd["orlis"][0:4]==[1,1,0,0]: logging.warning( "Stop Loss Order Executed!") #warn.tradingWarning(" Stop Loss Order Executed!") pd["invested"]= False pd["fixed"] = False #position closed, the stra type is free pd["check"] = False else: pass else: pd = self.pairs_dict #pd["orlis"][0] = copy.copy(pd["orlis"][1]) pd["orlis"].pop(0) pd["orlis"].append(1) logging.info("not empty- orlis: "+str(pd["orlis"])) pd["invested"]= True pd["fixed"] = True #position closed, the stra type is free pd["check"] = True else: pass
def collect(today='2017-01-30'): print('ond import successfull') timeframe = "M5" it = datetime.strftime( datetime.strptime(today, "%Y-%m-%d") - timedelta(days=2), "%Y-%m-%d") finish = datetime.strftime( datetime.strptime(today, "%Y-%m-%d") + timedelta(days=1), "%Y-%m-%d") print(it, finish) oanda = ond.API( environment='practice', access_token= 'ce5f70d5af3563435fa23311d05314ea-98f884f4751f25ff622cfa2debfbb01e') data = oanda.get_history( instrument='EUR_GBP', # our instrument start=it, # start data end=finish, # end date granularity=timeframe) # minute bars # 71 df = pd.DataFrame(data['candles']) # print(pd.DataFrame(data['candles'])) df['Date'] = pd.to_datetime(df.time) df.sort_values(by=['Date']) df['close'] = (df['closeBid'] + df['closeAsk']) / 2 #print(df) print('collect() done') df['pct'] = df['close'].pct_change() return (df)
def __init__(self, user_settings): HistoricalMarketData.__init__(self, user_settings) self.user_settings = user_settings self.oanda = oandapy.API( environment=self.user_settings.oanda_environment, access_token=self.user_settings.oanda_token) pass
def getDataBatch(startTime="0", instrument="EUR_USD"): account = od.API(environment="practice", access_token="", headers={'X-Accept-Datetime-Format': 'UNIX'}) hist = account.get_history(instrument="EUR_USD", granularity="M1", start=startTime, count="5000", candleFormat="midpoint") data = hist['candles'] close = np.ndarray([0]) high = np.ndarray([0]) low = np.ndarray([0]) volume = np.ndarray([0]) openMid = np.ndarray([0]) time = np.ndarray([0]) for x in data: cur = x close = np.append(close, float(cur.get('closeMid'))) high = np.append(high, float(cur.get('highMid'))) low = np.append(low, float(cur.get('lowMid'))) volume = np.append(volume, float(cur.get('volume'))) openMid = np.append(openMid, float(cur.get('openMid'))) time = np.append(time, float(cur.get('time'))) return close, high, low, volume, openMid, time
def __init__(cls): cfg = Config() cls.account_id = cfg.get_oanda_env('account_id') cls.api_key = cfg.get_oanda_env('api_key') cls.environment = cfg.get_oanda_env('environment') cls.oanda = oandapy.API(environment=cls.environment, access_token=cls.api_key)
def get_history_frame(instrument='EUR_USD', start=OandaDate().minus(minutes=1), end=OandaDate(), granularity=OandaGranularity.s5["api"]): config = configparser.ConfigParser() config.read(os.path.join(config_path, "oanda.cfg")) oanda = opy.API(environment='practice', access_token=config['oanda']['access_token']) try: data = oanda.get_history(instrument=instrument, start=str(start), end=str(end), granularity=granularity, price="M") data_frame = pd.DataFrame(data['candles']).set_index('time') data_frame.index = pd.DatetimeIndex(data_frame.index) print( data_frame, "Data received for instrument {} between {} and {}:".format( instrument, start.description(), end.description())) return data_frame except JSONDecodeError: print( "No Data received for instrument {} between {} and {}".format( instrument, start.description(), end.description()))
def download(target_year="2018", target=None): access_token = "e2d515e8591ad375131f73b4d00fa046-dbcc42f596456f1562792f3639259b7f" start_time = "T00:00:00" end_time = "T23:59:59" granularity = "H1" oanda = oandapy.API(environment="practice", access_token=access_token) for target in target_list: res_hist = oanda.get_history(instrument=target, granularity=granularity, start=target_year + "-01-01" + start_time, end=target_year + "-06-30" + end_time) rate1 = pandas.DataFrame(res_hist['candles']) time.sleep(1) res_hist = oanda.get_history(instrument=target, granularity=granularity, start=target_year + "-07-01" + start_time, end=target_year + "-12-31" + end_time) rate2 = pandas.DataFrame(res_hist['candles']) pandas.concat([rate1, rate2]).to_csv(target + "-" + granularity + "-" + target_year + ".csv", sep=",") print(target_year + ": " + str(target))
def __init__(self, user_settings): self.user_settings = user_settings self.oanda = oandapy.API( environment=self.user_settings.oanda_environment, access_token=self.user_settings.oanda_token) self.account_id = self.user_settings.oanda_id pass
def getDataCSV(pair, granularity, numDataPoints, OHLCV, time, ratio): oanda = oandapy.API(environment=environment, access_token=access_token) end = datetime.utcnow() if OHLCV: file = open(pair+'_'+granularity+'_'+str(numDataPoints)+'_OHLCV.csv', 'w') else: file = open(pair+'_'+granularity+'_'+str(numDataPoints)+'.csv', 'w') #can get max 5k datapoints in 1 call to the API count = 5000 data = [] print "getting data" while numDataPoints > 0: if numDataPoints < 5000: count = numDataPoints print end.isoformat('T') response = oanda.get_history(instrument = pair, granularity=granularity, count = count, candleFormat="midpoint", end=end.isoformat('T'))['candles'] end = parser.parse(response[0]["time"]) data += reversed(response) numDataPoints -= count for candle in reversed(data): if not OHLCV: if not time: file.write(str(candle['closeMid']) + '\n') else: file.write(str(candle['time'])+','+str(candle['closeMid']) + '\n') else: if not time: file.write(str(candle['openMid']) +',' + str(candle['highMid'])+','+str(candle['lowMid'])+','+str(candle['closeMid'])+','+str(candle['volume'])+ '\n') else: file.write(str(candle['time']) +','+ str(candle['openMid']) +',' + str(candle['highMid'])+','+str(candle['lowMid'])+','+str(candle['closeMid'])+','+str(candle['volume'])+ '\n')
def __init__(self, *args, **kwargs): oandapy.Streamer.__init__(self, *args, **kwargs) self.oanda = oandapy.API(kwargs["environment"], kwargs["access_token"]) self.instrument = None self.account_id = None self.qty = 0 self.ticks=0 self.resample_interval = "10s" self.mean_period_short = 12 self.mean_period_long = 24 self.buy_threshold = 1.0 self.sell_threshold = 1.0 self.resampled_prices=pd.DataFrame() self.prices = pd.DataFrame() self.beta = 0 self.is_position_opened = False self.opening_price = 0 self.executed_price = 0 self.unrealized_pnl = 0 self.realized_pnl = 0 self.position = 0 self.dt_format = "%Y-%m-%dT%H:%M:%S.%fZ"
def get_candles(dates, token): oanda = opy.API(environment="practice", access_token=token) data = oanda.get_history(instrument="EUR_USD", start=dates[0], end=dates[1], granularity="H1") return data["candles"]
def oanda(self): import oandapy if self._oanda is None: self._oanda = oandapy.API( environment=os.environ['OANDA_ENV'], access_token=os.environ['OANDA_ACCESS_TOKEN']) return self._oanda
def test_rest_connection(): """Initiate a connection, and get current EUR_USD price""" oanda = oandapy.API(access_token=settings.ACCESS_TOKEN, environment=settings.DOMAIN) response = oanda.get_prices(instruments=instruments) prices = response.get("prices") buy_price = prices[0].get("bid") print buy_price
def __init__(self): config = get_config() self.account_id = config.get_broker_account_id() self.environment = config.get_broker_environment() self.access_token = config.get_broker_access_token() self.api = oandapy.API( **{ "environment": config.get_broker_environment(), "access_token": config.get_broker_access_token(), })
def __init__(self, instrument, units, side, stopLoss, takeProfit): self.accountID = "8098814" self.token = "651c24e0df293921aa1d299195f42d9a-fb0a7be5c893a749d4593c2bef6e8730" self.response = dict() self.oanda = oandapy.API(environment="practice", access_token=self.token) self.instrument = instrument self.units = units self.side = side self.stopLoss = stopLoss self.takeProfit= takeProfit
def pause_plot(): fig, ax = plt.subplots(1, 1) #行数、列数1,1のオブジェクト生成 x_time = [datetime.datetime.now()] #oandapyの設定 oanda = oandapy.API( environment="practice", access_token= "e777fc0c0a7aedb89e00f91e15a7b415-ac361a890d2fa25b195ba4dbe825f38b") response = oanda.get_prices(instruments='USD_JPY') print(type(response)) prices = response.get('prices') asking_price = prices[0].get('ask') #yにレート入力 y = [asking_price] # 初期化的に一度plotしなければならない # そのときplotしたオブジェクトを受け取る受け取る必要がある. # listが返ってくるので,注意 lines, = ax.plot(x_time, y) # グラフのフォーマットの設定 cnt = 0 plt.grid(True) # ここから無限にplotする while True: cnt += 1 # plotデータの更新 response = oanda.get_prices(instruments='USD_JPY') prices = response.get('prices') asking_price = prices[0].get('ask') x_time.append(datetime.datetime.now()) y.append(asking_price) print(asking_price) # 描画データを更新するときにplot関数を使うと # lineオブジェクトが都度増えてしまうので,注意. # # 一番楽なのは上記で受け取ったlinesに対して # set_data()メソッドで描画データを更新する方法. lines.set_data(x_time, y) # set_data()を使うと軸とかは自動設定されないっぽいので, # そのためx軸の範囲は適宜修正してやる必要がある. ax.set_xlim(datetime.datetime.now() - datetime.timedelta(seconds=1000), datetime.datetime.now() + datetime.timedelta(seconds=10)) if cnt > 2: plt.ylim(min(y) - 0.01, max(y) + 0.01) # 一番のポイント # - plt.show() ブロッキングされてリアルタイムに描写できない # - plt.ion() + plt.draw() グラフウインドウが固まってプログラムが止まるから使えない # ----> plt.pause(interval) これを使う!!! 引数はsleep時間 plt.pause(1) if cnt > 100000: plt.close() break
def setUp(self): global access_token global account global api try: account, access_token = unittestsetup.auth() except Exception as e: print("%s" % e) exit(0) api = oandapy.API(environment=environment, access_token=access_token)
def collect(start='2018-01-30', end='2019-10-15'): a = ond.API( environment='practice', access_token= 'ce5f70d5af3563435fa23311d05314ea-98f884f4751f25ff622cfa2debfbb01e') print(dir(a)) print('ond import successfull') timeframe = "M5" dates = [] it = datetime.strptime(start, "%Y-%m-%d") finish = datetime.strptime(end, "%Y-%m-%d") while it < finish: dates.append(datetime.strftime(it, "%Y-%m-%d")) it += timedelta(days=14) dates.append(datetime.strftime(finish, "%Y-%m-%d")) oanda = ond.API( environment='practice', access_token= 'ce5f70d5af3563435fa23311d05314ea-98f884f4751f25ff622cfa2debfbb01e') for i in range(0, len(dates) - 1): print(dates[i], dates[i + 1]) data = oanda.get_history( instrument='EUR_GBP', # our instrument start=dates[i], # start data end=dates[i + 1], # end date granularity=timeframe) # minute bars # 7 print('data=', pd.DataFrame(data['candles'])) if i <= 0: df = pd.DataFrame(data['candles']) else: df = pd.concat([df, pd.DataFrame(data['candles'])], ignore_index=True) print(i) # print(pd.DataFrame(data['candles'])) df['Date'] = pd.to_datetime(df.time) df.sort_values(by=['Date']) df['close'] = (df['closeBid'] + df['closeAsk']) / 2 print(df) print('collect() done') return (df)
def StrategyMaker(): print('\n !!! Connecting User !!!') config = configparser.ConfigParser() # 3 config.read('oanda.cfg') # 4 oanda = opy.API(environment='practice', access_token=config['oanda']['access_token']) # 5 print('\n !!! Importing Market Data !!!') data = oanda.get_history( instrument='EUR_USD', # our instrument start='2017-11-24', # start data end='2017-11-26', # end date granularity='M1') # minute bars # 7 #data = oanda.rates(account_id=config['oanda']['account_id'], # instruments=['DE30_EUR'], ignore_heartbeat=True); print('\n !!! Creating DataFrame !!!') df = pd.DataFrame(data['candles']).set_index('time') # 8 df.index = pd.DatetimeIndex(df.index) # 9 #df.info() # 10 print('\n !!! Calculating Returns !!!') df['returns'] = np.log(df['closeAsk'] / df['closeAsk'].shift(1)) # 12 df.fillna(0, inplace=True) print('\n !!! Calculating Positions !!!') cols = [] # 13 for momentum in [15, 30, 60, 120]: # 14 col = 'position_%s' % momentum # 15 df[col] = np.sign(df['returns'].rolling(momentum).mean()) # 16 cols.append(col) # 17 sns.set() # 18 print('\n !!! Calculating strategy !!!') strats = ['returns'] # 19 for col in cols: # 20 strat = 'strategy_%s' % col.split('_')[1] # 21 df[strat] = df[col].shift(1) * df['returns'] # 22 strats.append(strat) # 23 #Get the best strategy Strat_Mean = {} for strat in strats: Strat_Mean[strat] = df[strat].mean() print(Strat_Mean) BestStrategy = max(Strat_Mean.items(), key=operator.itemgetter(1))[0] print('\n !!! Plot for various strategies and Returns !!!') df[strats].dropna().cumsum().apply(np.exp).plot() # 24 plt.show() return BestStrategy
def available_symbols(self): """ Get every symbols available for streaming by the broker :return: list of symbols """ if self.symbols is None: oanda = oandapy.API(environment=self.environment, access_token=self.token) symbols = oanda.get_instruments( account_id=self.account_id).get('instruments') return [symbol['instrument'] for symbol in list(symbols)] else: return self.symbols
def close_order(self, event): oanda0 = oandapy.API(environment="practice", access_token=self.access_token) response1= oanda0.get_trades(self.account_id,instrument=event.instrument) order_lis= response1["trades"] if order_lis !=[]: for order in order_lis: #close all trades responseX = oanda0.close_trade(self.account_id,trade_id= order['id']) logging.info( "Close Order ! \n {0}".format(responseX)) content0 = "Close Order !" + "profit: "+str(responseX['profit'])+" CLOSE "+str(responseX['instrument']) content0 = content0 + " "+str(responseX['side'])+" at "+ str(responseX['price']) #warn.tradingWarning(content0) else: logging.warning("No trade to be closed! :{0}".format(time.ctime()))
def close_all_trade(): oanda = oandapy.API(access_token=API_KEY, environment='practice') tickets = oanda.get_trades(account_id=ACCOUNT_ID)['trades'] for ticket in tickets: oanda.close_order(account_id=ACCOUNT_ID, order_id=ticket['id']) conn = sqlite3.connect(DB_NAME) c = conn.cursor() sql = "DELETE FROM chart_monitor;" c.execute(sql) sql = "DELETE FROM agent;" c.execute(sql) conn.close()
def run(self): credential = config.load()['oanda']['live'] oanda = oandapy.API(environment='live', access_token=credential['access_token']) while self.is_active(): try: res = oanda.get_prices(instruments=','.join(self.instruments)) for price in res['prices']: self.dispatch_price(price) except Exception as e: self.logger.exception(e) for _ in range(100): time.sleep(0.1) if not self.is_active(): break
def __init__(self): self.stds, self.means = self.load_scaler() self.sequential = rm.Sequential( [rm.Lstm(30), rm.Lstm(10), rm.Dense(pred_length)]) self.oanda = oandapy.API(environment="practice", access_token=token) self.res = self.oanda.get_history(instrument="USD_JPY", granularity=gran, count=look_back + pred_length + 78) self.prep = Preprocess(self.res) self.df = self.prep.data self.data = self.standardize() self.exp, self.target = self.create_dataset() self.pred = self.predict() self.pred_side = self.predict_side()
def __get_fx_data(self): """ oanda apiからjson fxデータを取得 :return: """ # 日時をapiのフォーマットに変換 from_datetime = FormatDatetime.datetime_to_str(self.from_datetime) to_datetime = FormatDatetime.datetime_to_str(self.to_datetime) # oanda apiで時系列fx価格データ取得 oanda = oandapy.API(environment="practice", access_token=ACCESS_TOKEN) self.json_fx_data = oanda.get_history(instrument=self.instrument, granularity=self.granularity, start=from_datetime, end=to_datetime, candleFormat='midpoint')
def getPrices(): oanda = oandapy.API(environment="practice", access_token=OANDA_API_KEY) lsymbol_id = [] f = open("symbolsLong.txt", "r") for x in f: sym = x.rstrip() lsymbol_id.append(sym) for x in lsymbol_id: systime.sleep(1) response = oanda.get_prices(instruments=x) prices = response.get("prices") asking_price = prices[0].get("ask") print("Symbol {} price {}".format(x, asking_price))
def __init__(self, environment, account_id, access_token, instrument): #一些账号个人信息 self.environment = environment self.account_id = account_id self.access_token = access_token self.oanda = oandapy.API(self.environment, self.access_token) self.instrument = instrument self.minute_granularity = 'M1' #分钟数据 self.hour_granularity = 'H1' #小时数据 self.minute_count = 5000 #5000分钟 self.hour_count = 20 #20小时 self.units = 1000 #下单数量:1000张合约 self.weighted_bias = 0 self.trading_stats = 0 self.ema1 = self.ema2 = self.ema3 = pd.Series() self.bias1 = self.bias2 = self.bias3 = pd.Series()
def main(): print "------ System online -------", datetime.now() oanda = oandapy.API(environment="practice", access_token=OANDA_ACCESS_TOKEN) response = oanda.get_prices(instruments="EUR_USD") prices = response.get("prices") buy_price = prices[0].get("bid") print "Buy at", buy_price trade_id = oanda.create_order(OANDA_ACCOUNT_ID, instrument="EUR_USD", units=1000, side='buy', type='market') print "Trading id", trade_id
def __init__(self, id, bid, ask): self.id = id self.bid = bid self.ask = ask self.HOLD = 0 self.BUY = 1 self.SELL = 2 self.CLOSE = 3 self.take_profit_pips = 30 self.stop_loss_pips = 15 self.point = 0.01 self.lots = 1 self.info = AccountInformation() self.oanda = oandapy.API(access_token=API_KEY, environment='practice') self.tickets = [ticket for ticket in self.get_active_tickets()]