【问题标题】:Python code issues with Oanda API Rest V20 - Unable to run automatic codeOanda API Rest V20 的 Python 代码问题 - 无法运行自动代码
【发布时间】:2018-06-03 03:06:04
【问题描述】:

这是我在这里的第一篇文章。当遇到一些代码问题时,我通常会找到我正在寻找的东西。不过这个不一样。

我正在尝试运行自动交易算法,但我在网上找到的帮助我编写此代码的东西要么已经过时,要么我猜我用错了。

因此,这是我的代码。第一部分工作得很好。到达“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)

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

【问题讨论】:

  • 嗨@Scapin,欢迎来到 StackOverflow!您能否在问题本身中发布您的代码,以便人们不需要导航到其他地方才能看到它?谢谢!
  • @raghav710 嗨,Raghav,是的,我想这更容易.. 很抱歉给您带来不便。你去吧!
  • 谢谢@Scapin
  • 您能否也发布您所面临的具体错误。任何事情,例如错误消息或您期望发生但未发生的事情,都应该没问题。
  • @raghav710 :我找到了我作为答案发布的代码的更新版本,所以现在它工作正常。 :)

标签: python algorithm api trading


【解决方案1】:

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

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

享受

【讨论】:

    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 2019-12-31
    • 2020-11-09
    • 1970-01-01
    相关资源
    最近更新 更多