Python code issues with Oanda API Rest V20 - Unabl

2019-09-01 16:16发布

问题:

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.

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!

回答1:

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

Enjoy