Oanda API Rest V20的Python代码问题-无法运行自动代码 [英] Python code issues with Oanda API Rest V20 - Unable to run automatic code

查看:222
本文介绍了Oanda API Rest V20的Python代码问题-无法运行自动代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在这里的第一篇文章。当遇到某些代码问题时,我通常会找到所需的内容。虽然这是不同的。

This is my first post on here. I usually find what i'm looking for when encountering issues with some codes. This one is different though.

我正在尝试运行自动交易算法,但是我在网上找到的可以帮助我编写此代码的东西要么过时,要么我猜我

I am trying to run an automatic trading algorithm but the stuff I found online to help me with writing this code is either outdated or i guess i'm using it wrong.

因此,这是我的代码。第一部分工作正常。到达 myclass部分时出现麻烦。

Thus, here is my code. The first part works perfectly fine. Trouble comes when arriving at the 'myclass' section.

CODE:

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)

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

Many thanks for your help if anyone can come up with a solution!

推荐答案

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

I found an updated version of the gist of the code I used to create the algorithm. That version works fine with oanda V20:

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

享受

这篇关于Oanda API Rest V20的Python代码问题-无法运行自动代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆