Oanda API Rest V20的Python代码问题 - 无法运行自动代码

时间:2018-06-02 14:13:59

标签: python algorithm api trading

这是我在这里发表的第一篇文章。我经常在遇到某些代码问题时找到我正在寻找的东西。但这个是不同的。

我正在尝试运行自动交易算法,但我在网上发现的帮助我编写此代码的内容要么过时,要么我猜错了。

因此,这是我的代码。第一部分完美无缺。到达“myclass'部分。

代码:

import json
import oandapyV20
from oandapyV20 import API    # the client
import oandapyV20.endpoints.instruments as instruments
import oandapyV20.endpoints.pricing as pricing

access_token = "<ACCESS_TOKEN>"
accountID = "<ACCOUNT_ID>"
client = API(access_token=access_token)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

params = {
  "count": 2880,
  "granularity": "M1",
  "from": "2016-12-08"
  }
r = instruments.InstrumentsCandles(instrument="EUR_USD", params=params)
client.request(r)
df = pd.DataFrame(r.response['candles'])
df1 = df['mid']

close_price = []
for i in range(len(df1)):
    close_price.append(df1[i]['c'])
df['close_price'] = close_price
first_algo = df.drop('mid',axis = 1)

test = []
for i in range(len(first_algo)):
    test.append(float(first_algo['close_price'][i]))
first_algo['prices'] = test
algo1 = first_algo.drop('close_price',axis = 1)

algo1['returns'] = np.log(algo1['prices'] / algo1['prices'].shift(1))


algo1['sign15'] = np.sign(algo1['returns'].rolling(15).mean().dropna())
algo1['strat15'] = algo1['sign15'].shift(1) * algo1['returns']
algo1['sign30'] = np.sign(algo1['returns'].rolling(30).mean().dropna())
algo1['strat30'] = algo1['sign30'].shift(1) * algo1['returns']
algo1['sign60'] = np.sign(algo1['returns'].rolling(60).mean().dropna())
algo1['strat60'] = algo1['sign60'].shift(1) * algo1['returns']
algo1['sign120'] = np.sign(algo1['returns'].rolling(120).mean().dropna())
algo1['strat120'] = algo1['sign120'].shift(1) * algo1['returns']

plt.plot(algo1['strat15'].cumsum().apply(np.exp))
plt.plot(algo1['strat30'].cumsum().apply(np.exp))
plt.plot(algo1['strat60'].cumsum().apply(np.exp))
plt.plot(algo1['strat120'].cumsum().apply(np.exp))
plt.plot(algo1['returns'].cumsum().apply(np.exp))
plt.show()

class MyTrader(oandapyV20.Streamer):
    def __init__(self,*args, **kwargs):
    pricing.__init__(self,**kwargs)
    self.ticks = 0
    self.position = 0
    self.df = pd.DataFrame()
    self.momentum = 60
    self.units(100000)
def create_order(self,side,units):

    order = oandapyV20.create_order(client,instrument = "EUR_USD", units = units, side = side, type = 'market')
    print('\n', order)
def on_success(self,data):
    self.ticks += 1
    self.df = self.df.append(pd.DataFrame(data['tick'],index = [data['tick']['time']]))
    self.df.index = pd.DatetimeIndex(self.df['time'])
    dfr = self.dr.resample('5s').last()
    dfr['returns'] = np.log(dfr['ask'] / dfr['ask'].shift(1))
    dfr['position'] = np.sign(dfr['returns'].rolling(self.momentum).mean().dropnap())
    if dfr['position'].ix[-1] == 1:
        if self.position == 0:
            self.create_order('buy',self.units)
        elif self.position == -1:
            self.create_order('buy',self.units * 2)
        self.position = 1
    elif dfr['position'].ix[-1] == -1:

        if self.position == 0:
            self.create_order('sell',self.units)
        elif self.position == 1:
            self.create_order('sell',self.units * 2)
        self.position = -1
    if self.ticks == 250:
        if self.position == 1:
            self.create_order('sell',self.units)
        elif self.position == -1:
            self.create_order('buy',self.units)
        self.disconnect()

mt = MomentumTrader(momentum=12, environment = 'practice', access_token = "1eee52a9fde16174d6d5d61ebaf78f07-d051b5059a8ff624844afeb10ed7a48d" )
mt.rates(account_id = '101-004-8530384-001',instruments=['EUR_USD'],ignore_heartbeat = True)

非常感谢您的帮助,如果有人能提出解决方案的话!

1 个答案:

答案 0 :(得分:1)

我找到了用于创建算法的代码要点的更新版本。该版本适用于oanda V20:

https://gist.github.com/benjaminchodroff/133e9913b37bff5d414bb8e6b71d0141#file-oandamomentumv20-ipynb

享受