Esempio n. 1
0
 def __init__(self):
     self.instrument = 'EUR_USD'
     self.balance = 100
     self.shoulder = 100
     self.client = Client(
         environment=PRACTICE,
         account_id=settings.ACCOUNT,
         access_token=settings.TOKEN
     )
     self.instruments_list = self.get_instruments()
Esempio n. 2
0
 def connect(self):
     try:
         self.client = Client(environment=PRACTICE,
                              account_id=self.set_obj.get_account_id(),
                              access_token=self.set_obj.get_token())
         print self.underlying + ' connection succeeded...'
     except:
         print self.underlying + ' connection failed...'
         time.sleep(5)
         self.connect()
Esempio n. 3
0
def creatDefaultClient(client=defautClient):
    if client is not None:
        return client

    client = Client(**Clients['pyoanda'])

    return client
Esempio n. 4
0
def practice ( ):
    con = Client(
        environment = PRACTICE,
        account_id = "5828851",
        access_token = "1781315285cf9234a14e0f7434cb7abf-7fa1e5faf584a0cbfc79553e7c2b0c2b"
    )
    return con
Esempio n. 5
0
class BaseTrade(object):
    def __init__(self):
        self.instrument = 'EUR_USD'
        self.balance = 100
        self.shoulder = 100
        self.client = Client(
            environment=PRACTICE,
            account_id=settings.ACCOUNT,
            access_token=settings.TOKEN
        )
        self.instruments_list = self.get_instruments()

    def get_instruments(self):
        return self.client.get_instruments()

    def back_testing(self, dataframe, strategy, trade_obj):
        BackTesting(dataframe, strategy, self.balance, self.instrument, self.instruments_list, trade_obj)
# instrument_string = 'EUR_USD,USD_JPY,GBP_USD,USD_CAD,USD_CHF,AUD_USD,CAD_JPY,BCO_USD,XAU_USD,XAG_USD'
# term1 = 'dollar'
# term2 = 'yen'

# accountID = "101-004-3748257-001"
# access_token="2b557bdd4fa3dee56c8a159ece012a48-5f5a29d25cb2e7ea1aaeba98f4bbca40"
# instruments = "EUR_USD,USD_JPY,GBP_USD,USD_CAD,USD_CHF,AUD_USD,CAD_JPY,BCO_USD,XAU_USD,XAG_USD"

accountID = "101-004-3748257-001"
access_token = "2b557bdd4fa3dee56c8a159ece012a48-5f5a29d25cb2e7ea1aaeba98f4bbca40"
instruments = "EUR_USD,USD_JPY,GBP_USD,USD_CAD,USD_CHF,AUD_USD,AUD_CAD,AUD_JPY,EUR_CHF,CAD_JPY,CHF_JPY"

client = Client(
    environment=PRACTICE,
    account_id='9276489',
    access_token=
    '2b557bdd4fa3dee56c8a159ece012a48-5f5a29d25cb2e7ea1aaeba98f4bbca40')


def connect_v20(access_token, accountID, instruments):
    api = API(access_token=access_token, environment="practice")
    s = PricingStream(accountID=accountID, params={"instruments": instruments})
    response = api.request(s)
    try:
        n = 0
        for R in api.request(s):
            # print (msg['type'])
            if R['type'] == 'HEARTBIT':
                print(json.dumps(R['type'], indent=2),
                      json.dumps(R['type']['time'], indent=2))
Esempio n. 7
0
import datetime

from pyoanda import Client, PRACTICE, Order

client = Client(
    environment=PRACTICE,
    account_id='9276489',
    access_token=
    '2b557bdd4fa3dee56c8a159ece012a48-5f5a29d25cb2e7ea1aaeba98f4bbca40')

test_order = Order(
    instrument="BCO_USD",
    units=1000,
    side="buy",
    type="market",
    trailingStop=51.10,
    takeProfit=58.55,
    # price=1.1100,
    # now = datetime.datetime.now()
    # expire = now + datetime.timedelta(days=1)
    # expiry="GTC"
    expiry=(datetime.datetime.now() +
            datetime.timedelta(days=50)).isoformat('T') + "Z"

    # expiry=(datetime.datetime.now() + datetime.timedelta(days=1))
    # expiry=datetime.datetime.now()
)

position = client.get_positions()
print(position)
order = client.create_order(order=test_order)
Esempio n. 8
0
#
# YAML format, please see:
#    http://ess.khhq.net/wiki/YAML_Tutorial
#
# Config file for connecting to Oanda
#
# ACCOUNT_NUM: Integer number
# ACCOUNT_KEY: String of your account Key


with open("Config.yaml") as f:
    config = yaml.load(f.read())

client = Client(
    TRADE,
    account_id=config['ACCOUNT_NUM'],
    access_token=config['ACCOUNT_KEY']
)

DAYS = 50
GRAN = 'M15'
INST = 'EUR_JPY'
start = datetime.now() - timedelta(days=DAYS)

with open('data/data-set-{}-days.csv'.format(DAYS), 'w') as f:

    # We will map fields of the returned data to a more human readable format.
    mapFields = {}

    # Remove ""Mids", remove "Complete"
    mapFields['time'] = 'time'
Esempio n. 9
0
from pyoanda import Client, SANDBOX

client = Client(environment=SANDBOX)

# Get prices for a list of instruments

pair_list = ('AUD_CAD', 'AUD_CHF')

dataset = client.get_prices(instruments=','.join(pair_list), stream=False)
"""
Response sample
{
    "prices": [
        {
            "ask": 81.551,
            "bid": 81.53,
            "instrument": "AUD_JPY",
            "time": "2016-01-26T07:39:56.525788Z"
        },
        {
            "ask": 127.975,
            "bid": 127.957,
            "instrument": "EUR_JPY",
            "time": "2016-01-26T07:39:55.712253Z"
        },
        {
            "ask": 167.269,
            "bid": 167.239,
            "instrument": "GBP_JPY",
            "time": "2016-01-26T07:39:58.333404Z"
        },
Esempio n. 10
0
class HFtrading:
    def __init__(self, underlying, set_obj):
        run_time = time.strftime("%Y%m%d_%H%M%S")
        self.underlying = underlying
        self.set_obj = set_obj
        self.mid_price = 0
        self.vol = None
        log_dir = '/Users/MengfeiZhang/Desktop/tmp'
        self.f = open(
            log_dir + '/' + self.underlying + '_hf_log_' + run_time + '.txt',
            'w')
        self.weekday = None
        self.now = None
        self.client = None
        self.q = 0
        self.max_inventory = set_obj.get_max_inventory()
        if ('JPY' in self.underlying) == True:
            self.prec = 3
        else:
            self.prec = 5
        #connect
        self.connect()
        sabr_calib = SABRcalib(0.5, 1.0 / 52)
        sabr_calib.calib(self.get_hist_data(262 * 5))
        self.SABRpara = sabr_calib.get_para()

    def connect(self):
        try:
            self.client = Client(environment=PRACTICE,
                                 account_id=self.set_obj.get_account_id(),
                                 access_token=self.set_obj.get_token())
            print self.underlying + ' connection succeeded...'
        except:
            print self.underlying + ' connection failed...'
            time.sleep(5)
            self.connect()

    def get_mid_price(self):
        try:
            price_resp = self.client.get_prices(instruments=self.underlying,
                                                stream=False)  #, stream=True
            price_resp = price_resp['prices'][0]
            return (price_resp['ask'] + price_resp['bid']) / 2
        except Exception as err:
            print >> self.f, err

    def get_atm_vol(self):
        return self.SABRpara[0] * self.get_mid_price()**(self.SABRpara[1] - 1)

    def get_hist_data(self, hist_len):
        hist_resp = self.client.get_instrument_history(
            instrument=self.underlying,
            candle_format="midpoint",
            granularity="D",
            count=hist_len,
        )
        price = []
        for i in range(0, len(hist_resp['candles'])):
            price.append(hist_resp['candles'][i]['closeMid'])

        return price

    def get_hist_vol(self):

        hist_resp = self.client.get_instrument_history(
            instrument=self.underlying,
            candle_format="midpoint",
            granularity="S5",
            count=100,
        )

        ret_tmp = []
        for i in range(1, len(hist_resp['candles'])):
            ret_tmp.append(hist_resp['candles'][i]['closeMid'] -
                           hist_resp['candles'][i - 1]['closeMid'])

        return np.std(ret_tmp)

    def get_live_sprd(self):
        try:
            price_resp = self.client.get_prices(instruments=self.underlying,
                                                stream=False)  #, stream=True
            price_resp = price_resp['prices'][0]
            return price_resp['ask'] - price_resp['bid']
        except Exception as err:
            print >> self.f, err
            return 0

    def get_current_inventory(self):
        return float(self.get_position()) / self.max_inventory

    def get_position(self):
        try:
            resp = self.client.get_position(instrument=self.underlying)
            if resp['side'] == 'buy':
                return resp['units']
            elif resp['side'] == 'sell':
                return -resp['units']
        except Exception as err:
            return 0

    def load_data(self):
        self.mid_price = self.get_mid_price()
        self.weekday = datetime.datetime.today().weekday()
        self.now = datetime.datetime.now()
        self.q = self.get_current_inventory()
        #self.vol=self.get_atm_vol()
        self.vol = self.get_hist_vol()

    def start(self):
        self.load_data()
        if (int(self.weekday) == 4 and int(self.now.hour) >= 17):  #Friday 5pm
            print 'market closed...'
            return None

        model = HFmodel(self.vol)
        model.calib(self.get_live_sprd())
        model.calc(self.mid_price, self.q, 0, 1)

        print >> self.f, 'market mid price: ' + str(self.mid_price)
        print >> self.f, 'model reservation price: ' + str(
            model.get_mid_rev_price())
        print >> self.f, 'model bid price: ' + str(model.get_opt_bid(
            self.prec))
        print >> self.f, 'model ask price: ' + str(model.get_opt_ask(
            self.prec))
        print >> self.f, 'gamma: ' + str(model.gamma)
        print >> self.f, 'inventory: ' + str(self.q)
        print >> self.f, 'volatility (5s): ' + str(self.vol)

        try:
            print 'heartbeat(' + self.underlying + ') ' + str(self.now) + '...'
            #close all outstanding orders
            resp_order = self.client.get_orders(instrument=self.underlying)
            for order in resp_order['orders']:
                resp_close_order = self.client.close_order(
                    order_id=order['id'])

            expiry_order = self.now + datetime.timedelta(days=1)
            expiry_order = expiry_order.isoformat('T') + "Z"
            order_ask = Order(
                instrument=self.underlying,
                units=self.set_obj.get_trade_size(),
                side="sell",
                type="limit",
                price=model.get_opt_ask(self.prec),
                expiry=expiry_order,
            )

            order_bid = Order(
                instrument=self.underlying,
                units=self.set_obj.get_trade_size(),
                side="buy",
                type="limit",
                price=model.get_opt_bid(self.prec),
                expiry=expiry_order,
            )
            #place order
            try:
                if self.q >= 1:  #long limit reached
                    resp_order_ask = self.client.create_order(order=order_ask)
                elif self.q <= -1:  #short limit reached
                    resp_order_bid = self.client.create_order(order=order_bid)
                else:
                    resp_order_ask = self.client.create_order(order=order_ask)
                    resp_order_bid = self.client.create_order(order=order_bid)
            except Exception as err:
                print err
                if ('halt' in str(err)) == True:
                    print 'market closed...'
                    return None
                else:
                    print "cannot place order..."

            time.sleep(self.set_obj.get_timer())
        except Exception as error:
            print error
            print self.underlying + ' disconnected, try to reconnect ' + str(
                self.now) + '...'
            self.connect()

        threading.Timer(1, self.start).start()
Esempio n. 11
0
"""How to create a stop order without pulling out all your hair :-)
"""
import datetime

from pyoanda import Client, SANDBOX, Order

client = Client(environment=SANDBOX)

test_order = Order(instrument="EUR_JPY",
                   units=10,
                   side="buy",
                   type="stop",
                   stopLoss=80.95,
                   takeProfit=170.56,
                   price=10.0,
                   expiry=datetime.datetime.now() + datetime.timedelta(days=1))

stop_order = client.create_order(order=test_order)
Esempio n. 12
0
File: algo.py Progetto: pymint/algo
    },
    # 'US2000_USD': {'buy_sl': 0.04,'buy_tp': 0.06,'dev': 1.8,'sell_sl': 0.045,'sell_tp': 0.055,'tf': 'D','units': 1},
    # 'WHEAT_USD': {'buy_sl': 0.03,'buy_tp': 0.04,'dev': 2,'sell_sl': 0.03,'sell_tp': 0.035,'tf': 'H6','units': 40},
    'WTICO_USD': {
        'buy_sl': 0.075,
        'buy_tp': 0.11,
        'dev': 1.9,
        'sell_sl': 0.063,
        'sell_tp': 0.08,
        'tf': 'D',
        'units': 1
    }
}

#####################################################
client = Client(environment=PRACTICE, account_id="", access_token="")


#####################################################
def plot_me(df, plr, symbol):
    import matplotlib.pyplot as plt
    df['close'].plot()
    plt.plot(plr, 'c-')
    plt.plot(df['stdev_up'], 'r')
    plt.plot(df['stdev_down'], 'r')
    x = list(range(len(df['close'])))
    for i in range(len(df['close'])):
        plt.plot((x[i], x[i]), (df['low'][i], df['high'][i]),
                 '0.4',
                 linewidth=1)
    ax = plt.gca()
Esempio n. 13
0
def run():
    symbol = input("Enter ticker symbol: ")

    now = dt.datetime.now()
    timeFinish = now + dt.timedelta(minutes=minutes)

    while (now < timeFinish):
        try:
            now = dt.datetime.now()

            client = Client(environment=PRACTICE,
                            account_id="",
                            access_token=ACCESS_TOKEN)

            json_data = []

            json_data = client.get_instrument_history(instrument=symbol,
                                                      granularity=timeframe,
                                                      candle_format="midpoint",
                                                      count=1440)
            json_data = json_data['candles']
            df = pd.DataFrame(json_data)

            data = df.copy()
            data = data.set_index('time')[['closeMid']]
            data = data.set_index(pd.to_datetime(data.index))
            data.columns = [CLOSE]

            # Rescale data
            lnprice = np.log(data)

            # Create and fit the model
            model_temp = auto_arima(lnprice.values,
                                    start_p=1,
                                    start_q=1,
                                    max_p=1,
                                    max_q=1,
                                    m=4,
                                    start_P=0,
                                    seasonal=False,
                                    d=1,
                                    D=1,
                                    trace=True,
                                    error_action='ignore',
                                    suppress_warnings=True,
                                    stepwise=True)

            model = ARIMA(order=model_temp.order)
            fit = model.fit(lnprice.values)

            # Predict
            future_forecast = fit.predict(n_periods=n_periods_ahead)
            future_forecast = np.exp(future_forecast)

            # Calculations
            lowest = min(future_forecast[0], future_forecast[-1])
            highest = max(future_forecast[0], future_forecast[-1])
            current = data[CLOSE].iloc[-1]
            x = ((future_forecast[0] - future_forecast[-1]) /
                 future_forecast[0]) * 100
            slope = (future_forecast[0] -
                     future_forecast[-1]) / n_periods_ahead
            degree = math.degrees(math.atan(slope))

            # Trending
            if (x > 0):
                trending = "Positivly / Call"
            else:
                trending = "Negativaly / Put"

            # View
            print("==========================")
            print("Current Price: ", current)
            print("Highest price: ", highest)
            print("Lowest Price: ", lowest)
            print("Trending: ", trending)
            print("Degrees: ", degree)
            print("==========================" + "\n")
        except Exception as e:
            print(e)

        time.sleep(SLEEP)

    return 0
Esempio n. 14
0
from pyoanda import Client, PRACTICE
from pyoanda.exceptions import BadRequest
from datetime import datetime, timedelta

client = Client(
    PRACTICE,
    account_id="2015316",
    access_token=
    "d2165c62b827b4ecc7c8d6e902cffc00-b65a089471813642049226e1ec9fc935")

INSTRUMENT = "EUR_USD"
DAYS = 365
end = datetime.now()
import csv
with open('data-set-{}-{}-days.csv'.format(INSTRUMENT, DAYS), 'w') as f:
    fields = [
        'time', 'lowBid', 'closeBid', 'openAsk', 'closeAsk', 'complete',
        'openBid', 'highAsk', 'lowAsk', 'highBid', 'volume'
    ]
    writer = csv.DictWriter(f, fieldnames=fields)
    writer.writeheader()
    for _ in range(DAYS):
        f.flush()
        for _ in range(2):  # 24/12 hours
            start = end - timedelta(hours=12)
            kwargs = dict(instrument=INSTRUMENT,
                          candle_format="bidask",
                          granularity="S5",
                          count=None,
                          start=start.strftime("%Y-%m-%dT%H:%M:%S.%f%z"),
                          end=end.strftime("%Y-%m-%dT%H:%M:%S.%f%z"))