예제 #1
0
def collectData(instrument, granularity, count):
    candleData = requests.get(accountDetails.getBaseURL() + "instruments/" +
                              instrument + "/candles",
                              headers=accountDetails.getHeaders(),
                              params=createQuery(granularity, count))
    parsedData = json.loads(json.dumps(candleData.json()))
    candles = parsedData["candles"]
    return candles
예제 #2
0
def collectData(instrument, granularity, count):
    candleData = requests.get(accountDetails.getBaseURL() + "instruments/" +
                              instrument + "/candles",
                              headers=accountDetails.getHeaders(),
                              params=createQuery(granularity, count))
    parsedData = json.loads(json.dumps(candleData.json()))
    candles = parsedData["candles"]
    RSIs, avgSog, avgSol = RSICalculation.calcRSI(14, candles)
    stopLevel = trailingStopLevel.main(candles)
    return candles, RSIs
예제 #3
0
def openTradeTrailing(instrument):

    ##Current price chunk
    rawCandle = requests.get(accountDetails.getBaseURL() + "/instruments/" + instrument + "/candles",
                             headers=accountDetails.getHeaders(), params=createQuery("M5", 3))
    parsedCandle = json.loads(json.dumps(rawCandle.json()))

    ##curentPrice is live price -- only using completed candles##
    currentPrice1 = float(parsedCandle["candles"][2]["mid"]["c"])



    bestStopFloat = float(backtestStream.getBestStop(candles, RSIs))

    takeProfitPrice = "{0:.4f}".format(bestStopFloat + currentPrice1)

    mktOrderParamsTrailing["instrument"] = instrument
    mktOrderParamsTrailing["order"]["takeProfitOnFill"]["price"] = takeProfitPrice

    result = requests.post(accountDetails.getBaseURL() + "/accounts/" + accountDetails.accountID + "/orders", headers = accountDetails.getHeaders(), json = mktOrderParamsTrailing)
    print(result)

    print("Trade entered with the following parameters:")


    ##get entry price##
    resultBody = json.loads(json.dumps(result.json()))
    print(resultBody)
    entryPrice = float(resultBody["orderFillTransaction"]["price"])

    print("Entry price: " + str(entryPrice))
    print("Take Profit: " + str(float(resultBody["orderCreateTransaction"]["takeProfitOnFill"]["price"]) - entryPrice))
    print("Stop Loss: " + str(float(resultBody["orderCreateTransaction"]["stopLossOnFill"]["distance"])))

    ##get tradeId##
    tradeId = resultBody["orderFillTransaction"]["id"]


    tradeIsOpen = True

    currentTime = time.clock()
    exitTime = currentTime + 60
    emailer.sendEmail(instrument,entryPrice)
    while tradeIsOpen:
        time.sleep(400)
        tradeIsOpenA = checkForOpen(instrument)

        if not tradeIsOpenA[0]:
            tradeIsOpen = False
        else:
            print("Trade is open. PL: " + str(tradeIsOpenA[1]))



    print(result)
예제 #4
0
def checkForOpen(instrument):
    positionsRaw = requests.get(accountDetails.getBaseURL() + "accounts/" +
                                accountDetails.accountID + "/openPositions",
                                headers=accountDetails.getHeaders())
    print(positionsRaw)
    parsedData = json.loads(json.dumps(positionsRaw.json()))
    positions = parsedData["positions"]
    for position in positions:
        if instrument == position["instrument"]:
            return [True, position["long"]["unrealizedPL"]]
    return [False, 0]
예제 #5
0
def collectData(instrument, granularity, fromTime, toTime):

    fromTime = str(fromTime.isoformat("T")) + "Z"
    toTime = str(toTime.isoformat("T")) + "Z"
    candleData = requests.get(
        accountDetails.getBaseURL() + "instruments/" + instrument + "/candles",
        headers=accountDetails.getHeaders(),
        params=createQuery(granularity, fromTime, toTime))
    parsedData = json.loads(json.dumps(candleData.json()))
    #print(parsedData)
    candles = parsedData["candles"]
    return candles
예제 #6
0
def checkForOrder(instrument):
    ordersRaw = requests.get(accountDetails.getBaseURL() + "accounts/" +
                             accountDetails.accountID + "/orders?instrument=" +
                             instrument,
                             headers=accountDetails.getHeaders())
    print(ordersRaw)
    parsedData = json.loads(json.dumps(ordersRaw.json()))
    orders = parsedData["orders"]
    if len(orders) > 0:
        return True

    return False
예제 #7
0
def collectDataCount(instrument, granularity, count):

    candleData = requests.get(accountDetails.getBaseURL() + "instruments/" +
                              instrument + "/candles",
                              headers=accountDetails.getHeaders(),
                              params=createQueryCount(granularity, count))
    parsedData = json.loads(json.dumps(candleData.json()))
    candles = parsedData["candles"]

    prices = []
    volumes = []
    for candle in candles:
        prices.append(float(candle['mid']['c']))
        volumes.append(float(candle['volume']))
    return prices, volumes
예제 #8
0
def getCurrentPrice(instrument, long=False, short=False):
    query = {"granularity": "M1", "count": 2}

    rawCandle = requests.get(accountDetails.getBaseURL() + "/instruments/" +
                             instrument + "/candles",
                             headers=accountDetails.getHeaders(),
                             params=query)
    parsedCandle = json.loads(json.dumps(rawCandle.json()))

    ##curentPrice is live price -- only using completed candles##
    currentPrice1 = float(parsedCandle["candles"][-1]["mid"]["c"])

    if long:
        cp = float(parsedCandle["candles"][-1][""]["c"])

    return "{0:.4f}".format(currentPrice1)
예제 #9
0
def open_trade(instrument, params):

    try:
        result = requests.post(accountDetails.getBaseURL() + "/accounts/" +
                               accountDetails.accountID + "/orders",
                               headers=accountDetails.getHeaders(),
                               json=params)
        resultBody = json.loads(json.dumps(result.json()))

        print(resultBody)
        entryPrice = float(resultBody["orderFillTransaction"]["price"])

        emailer.sendEmail(instrument, entryPrice)
        print("Entry price: " + str(entryPrice))

    except:
        print("Unable to enter trade...")
        traceback.print_exc()
예제 #10
0
    "granularity":"H1",
    "count" : 5000
}

def createQuery(granularity,count):
    ##granularities on http://developer.oanda.com/rest-live-v20/instrument-df/
    ## count is an int from 0 to 5000 inclusive
    query = {
        "granularity": granularity,
        "count": count
    }
    return query


instrument = "EUR_USD"
candleData = requests.get(accountDetails.getBaseURL() + "instruments/" + instrument + "/candles", headers=accountDetails.getHeaders(), params=query)
parsedData = json.loads(json.dumps(candleData.json()))
candles = parsedData["candles"]


rawCandle = requests.get(accountDetails.getBaseURL() + "/instruments/"+ instrument +"/candles", headers = accountDetails.getHeaders(), params = createQuery("M5",3))
parsedCandle = json.loads(json.dumps(rawCandle.json()))

##curentPrice is live price -- only using completed candles##
currentPrice1 = float(parsedCandle["candles"][2]["mid"]["c"])



mktOrderParamsTrailing = {
    "order": {
        "units": "800",
예제 #11
0
import statistics

import math
import requests
import json
import accountDetails



instrument = "EUR_USD"
query = {
    "granularity":"M15",
    "count" : 1000
}

candleData = requests.get(accountDetails.getBaseURL() + "instruments/" + instrument + "/candles", headers=accountDetails.getHeaders(), params=query)
parsedData = json.loads(json.dumps(candleData.json()))
candles = parsedData["candles"]


def candleChanges(candles):
    candleChangeList = []
    for i in range(1,len(candles)):
        change = float(candles[i]["mid"]["h"]) - float(candles[i]["mid"]["l"])
        candleChangeList.append(change)
    return candleChangeList




def main(candles):
예제 #12
0
def stream(RSI,avgSog,avgSol):
    ## True so it will run indefinitely (until I cancel it running or something goes wrong) ##

    c = 0
    while True:
        if c != 0:
            ##get current price data
            rawCandle = requests.get(accountDetails.getBaseURL() + "/instruments/"+ instrument +"/candles", headers = accountDetails.getHeaders(), params = createQuery("M5",3))
            parsedCandle = json.loads(json.dumps(rawCandle.json()))

            ##curentPrice is live price -- only using completed candles##
            currentPrice = float(parsedCandle["candles"][2]["mid"]["c"])

            p1Price = float(parsedCandle["candles"][1]["mid"]["c"])
            p2Price = float(parsedCandle["candles"][0]["mid"]["c"])

            priceChange = p1Price-p2Price

            ##update RSI##
            results = RSICalculation.updateRSI(priceChange,avgSog,avgSol)
            RSI = results[0]
            avgSog = results[1]
            avgSol = results[2]

        print("Waiting for trade...")
        print(RSI)
        print("\n")

        if RSI >= 70:
            print("Opening trade...")
            openTradeTrailing(instrument)

        print("RSI update in 5 minutes: " + str(datetime.datetime.now()))

        time.sleep(60*5)
        c+=1
예제 #13
0
def getTradeStatus(tradeId):
    tradeStatus = requests.get(accountDetails.getBaseURL() + "accounts/" + accountDetails.accountID + "/trades/" + tradeId, headers = accountDetails.getHeaders())
    parsedStatus = json.loads(json.dumps(tradeStatus.json()))

    print(tradeStatus)
    if parsedStatus["trade"]["state"] == "OPEN":
        return True
    else:
        return False
예제 #14
0
def stream(instrument, vwaps, vdists, candles):
    ## True so it will run indefinitely (until I cancel it running or something goes wrong) ##

    p_with_v = vwaps
    dist_from_price = vdists
    vwaps = []
    c = 0
    currentPrice = float(candles[-1]['mid']['c'])
    long_o = False
    short_o = False
    while True:
        if c != 0:
            ##get current price data
            rawCandle = requests.get(accountDetails.getBaseURL() +
                                     "/instruments/" + instrument + "/candles",
                                     headers=accountDetails.getHeaders(),
                                     params=createQuery("M1", 3))
            parsedCandle = json.loads(json.dumps(rawCandle.json()))

            candle = parsedCandle["candles"][1]
            candles.append(candle)

            p_with_v, dist_from_price = calcVWAPs(candles)

        print("Waiting for trade...")
        #print("VWAP:", p_with_v[-1][-1], "Price:", p_with_v[-1][0])
        #print("\n")

        price = p_with_v[-1][0]
        vwap = p_with_v[-1][-1]
        distance = (price - vwap) / price
        level = numpy.std(dist_from_price) * 3
        #print("Distance: ", abs(distance), " Level: ", level)
        tradeIsOn = checkForOpen(instrument)
        isOpen = tradeIsOn[0]

        long_entry_cond = abs(distance) > level and not isOpen and distance < 0
        short_entry_cond = abs(
            distance) > level and not isOpen and distance > 0
        open_order = checkForOrder(instrument)

        if not isOpen:

            if not open_order:
                if long_entry_cond:
                    long_params["price"] = getCurrentPrice(instrument)
                    end = datetime.datetime.utcnow() + datetime.timedelta(
                        minutes=5)
                    gtd = str(end.isoformat("T")) + "Z"
                    long_params["gtdTime"] = gtd
                    exe_price = open_trade(instrument, long_params)
                    long_o = True
                    print("Long ordered")

                elif short_entry_cond:
                    short_params["price"] = getCurrentPrice(instrument)
                    end = datetime.datetime.utcnow() + datetime.timedelta(
                        minutes=5)
                    gtd = str(end.isoformat("T")) + "Z"
                    short_params["gtdTime"] = gtd
                    exe_price = open_trade(instrument, short_params)
                    short_o = True
                    print("Short ordered")

        elif isOpen:
            long_exit_cond = vwap >= price
            short_exit_cond = vwap <= price

            if long_exit_cond:
                exe_price = open_trade(instrument, short_params)
                print("Long closed at: ", exe_price)
                long_o = False
            elif short_exit_cond:
                exe_price = open_trade(instrument, long_params)
                print("Short closed at: ", exe_price)
                short_o = False

        current_time = datetime.datetime.time(datetime.datetime.now())
        if current_time > datetime.time(
                hour=0, minute=0, second=0,
                microsecond=0) and current_time < datetime.time(
                    hour=0, minute=2, second=0, microsecond=0):
            if tradeIsOn[0]:
                if long_o:
                    exe_price = open_trade(instrument, short_params_exit)
                    print("Long closed")
                    long_o = False
                elif short_o:
                    exe_price = open_trade(instrument, long_params_exit)
                    print("Short closed")
                    short_o = False

        print("VWAP update in 1 minute: " + str(datetime.datetime.now()))

        time.sleep(60)
        c += 1