예제 #1
0
def get_pos():
    """
    get current positions
    """
    r = positions.OpenPositions(accountID=account_id)
    client.request(r)
    return r.response
예제 #2
0
파일: portopt.py 프로젝트: kev1n/algotwo
def openpositions():
    account_details = positions.OpenPositions(accountID=accountID)
    api.request(account_details)

    details = account_details.response

    return details
예제 #3
0
def get_open_positions(accountID, other_args):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="positions",
        description="Gets information about open positions.",
    )
    ns_parser = parse_known_args_and_warn(parser, other_args)
    if not ns_parser:
        return
    try:
        request = positions.OpenPositions(accountID)
        response = client.request(request)
        for i in range(len(response["positions"])):
            instrument = response["positions"][i]["instrument"]
            long_units = response["positions"][i]["long"]["units"]
            long_pl = response["positions"][i]["long"]["pl"]
            long_upl = response["positions"][i]["long"]["unrealizedPL"]
            short_units = response["positions"][i]["short"]["units"]
            short_pl = response["positions"][i]["short"]["pl"]
            short_upl = response["positions"][i]["short"]["unrealizedPL"]
            print(f"Instrument: {instrument}\n")
            print(f"Long Units: {long_units}")
            print(f"Total Long P/L: {long_pl}")
            print(f"Long Unrealized P/L: {long_upl}\n")
            print(f"Short Units: {short_units}")
            print(f"Total Short P/L: {short_pl}")
            print(f"Short Unrealized P/L: {short_upl}")
            print("-" * 30 + "\n")
        print("")

    except V20Error as e:
        d_error = eval(e.msg)
        print(d_error["errorMessage"], "\n")
예제 #4
0
class Position:
  # Load config
  conn = Connection.getInstance()
  accountID = conn.config['ACCOUNT_ID']

  q = positions.OpenPositions(accountID)
  data = conn.API.request(q)['positions']

  def __init__(self, i):
    self.pair = self.data[i]['instrument']
    self.long = self.data[i]['long']
    self.short = self.data[i]['short']

  def is_long(self):
    return True if self.long['units'] != '0' else False
  
  def is_short(self):
    return True if self.short['units'] != '0' else False

  @staticmethod
  def is_opened(pair):
    q = positions.OpenPositions(Position.accountID)
    for position in Connection.getInstance().API.request(q)['positions']:
      if position['instrument'] == pair:
        return True
예제 #5
0
def open_position():
    r_open = positions.OpenPositions(accountID=accountID)
    api.request(r_open)
    x = r_open.response
    x = x.get('positions')
    y = [z['instrument'] for z in x]
    return y
예제 #6
0
	def get_open_positions(self):
		open_positions = positions.OpenPositions(accountID=self._accountID)
		x = self._client.request(open_positions)['positions']
		dick = {}
		for i in x:
			dick[i['instrument']] = [int(i['short']['units']), int(i['long']['units'])]
			dick[i['instrument']] = dick[i['instrument']][0]+dick[i['instrument']][1]
		return dick
예제 #7
0
def open_positions():
    result = {}
    r = positions.OpenPositions(accountID=account_id)
    client.request(r)
    for p in r.response['positions']:
        result[p['instrument']] = p

    return result
예제 #8
0
def getOpenPosition():
    # Load config
    connection = Connection()
    accountID = connection.config['ACCOUNT_ID']

    # Request
    r = positions.OpenPositions(accountID)
    return connection.API.request(r)
예제 #9
0
 def test__openpositions_list(self, mock_get):
     """get the openpositions list for an account."""
     tid = "_v3_accounts_accountID_openpositions"
     resp, data = fetchTestData(responses, tid)
     r = positions.OpenPositions(accountID)
     mock_get.register_uri('GET',
                           "{}/{}".format(api.api_url, r),
                           text=json.dumps(resp))
     result = api.request(r)
     self.assertTrue(resp == result)
예제 #10
0
파일: oanda.py 프로젝트: adamstreu/forex
def get_open_positions(account):
    client = 'client=oandapyV20.API(access_token=env['client'])'
    client = oandapyV20.API(access_token=client)
    r = positions.OpenPositions(accountID=account)
    client.request(r)
    p = r.response
    instruments = []
    for position in p['positions']:
        instruments.append(position['instrument'])
    return instruments  
예제 #11
0
    def open_positions_info(self):

        import oandapyV20.endpoints.positions as positions

        r_p = positions.OpenPositions(accountID=self.accountID)
        self.client.request(r_p)
        open_pos = r_p.response

        for idx in range(len(open_pos["positions"])):
            self.open_positions.append(open_pos["positions"][idx]["instrument"])
예제 #12
0
 def get_open_position(self):
     try:
         postion = positions.OpenPositions(accountID=self.oanda_account_id)
         response = self.api.request(postion)
         print('get_open_position response', json.dumps(response, indent=2))
     except requests.exceptions.ConnectionError as e_HTTP:
         print(response.text)
         print(e_HTTP)
     except Exception as e:
         print(e)
         raise OandaApiError(e)
예제 #13
0
파일: oanda.py 프로젝트: adamstreu/diff
def get_open_positions(client=oanda_api, account_id=oanda_account):
    client = oandapyV20.API(access_token=client)
    r = positions.OpenPositions(account_id)
    client.request(r)
    p = r.response
    instruments = []
    for position in p['positions']:
        if float(position['long']['units']) > 0:
            instruments.append((position['instrument'], 'long'))
        else:
            instruments.append((position['instrument'], 'short'))
    return instruments
예제 #14
0
def oanda_market(side, lot):
    # lotが買いか売りを判定する
    if side == "BUY":
        units = lot
    if side == "SELL":
        units = -1 * lot

    # 注文内容
    order = {
        'order': {
            "instrument": currency,
            "units": units,
            "type": "MARKET",
            "positionFill": "DEFAULT"
        }
    }

    while True:
        try:
            # API取得
            api = API(access_token=token)
            order = orders.OrderCreate(accountID, data=order)
            position = positions.OpenPositions(accountID=accountID)
            # 注文実行
            api.request(order)  # API元にrequestを送る(order)
            position = api.request(position)  # API元にrequestを送る(position)
            time.sleep(20)

            if units > 0:
                average_price = position['positions'][0]['long'][
                    'averagePrice']
                print_log("チケットID : " + position['lastTransactionID'] +
                          "ロングポジションです")
                print_log(
                    "\nすべての成行注文が執行されました\n執行価格は平均 {}円です".format(average_price))
                return float(average_price)

            elif units < 0:
                average_price = position['positions'][0]['short'][
                    'averagePrice']
                print_log("チケットID : " + position['lastTransactionID'] +
                          "ショートポジションです")
                print_log(
                    "\nすべての成行注文が執行されました\n執行価格は平均 {}円です".format(average_price))
                return float(average_price)

        except V20Error as e:
            print_log("\nOANDAのAPIで問題発生\n" + str(e) + "\n20秒待機してやり直します")
            time.sleep(20)
예제 #15
0
def main():

    from configparser import ConfigParser
    import oandapyV20
    import oandapyV20.endpoints.positions as positions

    config = ConfigParser()
    config.read('oanda.ini')

    accountID = config.get('fxpractice', 'active_account')
    client = oandapyV20.API(access_token=config.get('fxpractice', 'token'))
    r = positions.OpenPositions(
        accountID=config.get('fxpractice', 'active_account'))
    client.request(r)
    print(r.response)
def update_positions():

    if not is_directory_locked():
        create_lock_file()
        try:
            # delete all current positions prior to update
            for fn in os.listdir(static.filepath): # loop through files in directory
                if 'position-' in fn:
                    os.remove(static.filepath+fn)

            if (static.live_trading):
                client = oandapyV20.API(static.token, environment='live')
            else:
                client = oandapyV20.API(static.token, environment='practice')

            response = positions.OpenPositions(static.account_id)
            rv = client.request(response)
            
            #print(rv["positions"])

            for position in rv["positions"]:
                longunits = int(position["long"]["units"])
                shortunits = int(position["short"]["units"]) * -1
                
                if(longunits > 0):
                    side = "buy"
                    units = position["long"]["units"]
                    avgPrice = position["long"]["averagePrice"]
                    total = len(position["long"]["tradeIDs"])
                if(shortunits > 0):
                    side = "sell"
                    units = abs(int(position["short"]["units"]))
                    avgPrice = position["short"]["averagePrice"]
                    total = len(position["short"]["tradeIDs"])
                # create file position-EUR_USD-buy-2500-1.13041
                file = open(static.filepath+"position-"+position.get("instrument")+".txt","w")
                file.write(side+","+
                           str(units)+","+
                           str(avgPrice)+","+
                           str(total))
                file.close()

            print("UPDATE POSITIONS: Success")
        except Exception as e:
            print(e)
        delete_lock_file()
    return
예제 #17
0
def live_positions(detail="basic"):
    """Request the open positions on the oanda account

    Parameters:
    detail (str): a basic matrix or the full matrix.

    Returns:
    dataframe: a matrix with 2 columns or a matrix withall columns.
    """

    current_positions = Positions.OpenPositions(accountID=accountID)
    client.request(current_positions)
    position_info = current_positions.response
    positions = position_info["positions"]
    with PRMS_Database() as db:
        instrument_names = db.get_db_instruments()

    position_details = []
    for position in positions:
        instrument = position["instrument"]
        instrument_name = instrument_names.get(instrument)

        if int(position["short"]["units"]) < 0:
            position_data = position["short"]

        elif int(position["long"]["units"]) > 0:
            position_data = position["long"]

        avg_price = position_data["averagePrice"]
        units = position_data["units"]
        pnl = position_data["pl"]
        unrel_pnl = position_data["unrealizedPL"]

        data = [instrument_name, units, avg_price, unrel_pnl, pnl]
        position_details.append(data)

    if len(position_details) == 0:
        print("There are no positions")
        return None

    if detail == "basic":
        return [row[0:2] for row in position_details]  # instrument name, units
    elif detail == "advanced":
        return position_details
    else:
        raise TypeError("detail should be 'basic' or 'advanced'")
예제 #18
0
 def oanda_getpositions(self, market = None):
     request = positions.OpenPositions(self.oanda_account_id)
     rv = self.oanda.request(request)
     result = []
     if market is not None:  # for specific market
         temp_dict = {}
         for elem in rv['positions']:
             if elem['instrument'] == market:
                 temp_dict = self.oanda_position_elem_process(elem, temp_dict)
         result.append(temp_dict)
     else: # for all markets
         for elem in rv['positions']:
             temp_dict = {}
             temp_dict = self.oanda_position_elem_process(elem, temp_dict)
             temp_dict['market'] = elem['instrument']
             if temp_dict != {}:
                 result.append(temp_dict)
     return result
예제 #19
0
def open_positions_request(
        accountID: str = account) -> Union[pd.DataFrame, bool]:
    """Request information on open positions.

    Parameters
    ----------
    accountID : str, optional
        Oanda account ID, by default cfg.OANDA_ACCOUNT
    """
    if accountID == "REPLACE_ME":
        console.print("Error: Oanda account credentials are required.")
        return False

    if client is None:
        return False

    try:
        request = positions.OpenPositions(accountID)
        response = client.request(request)
        position_data = []
        for i in range(len(response["positions"])):
            position_data.append({
                "Instrument":
                response["positions"][i]["instrument"],
                "Long Units":
                response["positions"][i]["long"]["units"],
                "Total Long P/L":
                response["positions"][i]["long"]["units"],
                "Unrealized Long P/L":
                response["positions"][i]["long"]["unrealizedPL"],
                "Short Units":
                response["positions"][i]["short"]["units"],
                "Total Short P/L":
                response["positions"][i]["short"]["pl"],
                "Short Unrealized P/L":
                response["positions"][i]["short"]["unrealizedPL"],
            })
        df_positions = pd.DataFrame.from_dict(position_data)
        return df_positions
    except V20Error as e:
        logger.exception(str(e))
        d_error = json.loads(e.msg)
        console.print(d_error["errorMessage"], "\n")
        return False
    def live_positions(self, detail="basic"):
        if not self.connection_status:
            return []
        position_endpoint = positions.OpenPositions(self._account_id)
        self._api_client.request(position_endpoint)
        response = position_endpoint.response
        current_positions = response["positions"]

        position_details = []
        # This violates DRY fix it
        if detail == "basic":
            for position in current_positions:
                instrument = position["instrument"]
                if int(position["short"]["units"]) < 0:
                    position_data = position["short"]

                elif int(position["long"]["units"]) > 0:
                    position_data = position["long"]
                units = position_data["units"]
                basic_position = OandaPositionsBasic(instrument, units)
                position_details.append(basic_position)

            return position_details
        elif detail == "advanced":
            for position in current_positions:
                instrument = position["instrument"]

                if int(position["short"]["units"]) < 0:
                    position_data = position["short"]

                elif int(position["long"]["units"]) > 0:
                    position_data = position["long"]

                avg_price = position_data["averagePrice"]
                units = position_data["units"]
                pnl = position_data["pl"]
                unrel_pnl = position_data["unrealizedPL"]
                advanced_position = OandaPositionsAdvanced(
                    instrument, units, avg_price, unrel_pnl, pnl)
                position_details.append(advanced_position)
            return position_details
        else:
            return None  # throw error in future
예제 #21
0
def get_open_positions(accountID, other_args):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="positions",
        description="Gets information about open positions.",
    )
    ns_parser = parse_known_args_and_warn(parser, other_args)
    if not ns_parser:
        return
    try:
        request = positions.OpenPositions(accountID)
        response = client.request(request)
        position_data = []
        for i in range(len(response["positions"])):
            position_data.append({
                "Instrument":
                response["positions"][i]["instrument"],
                "Long Units":
                response["positions"][i]["long"]["units"],
                "Total Long P/L":
                response["positions"][i]["long"]["units"],
                "Unrealized Long P/L":
                response["positions"][i]["long"]["unrealizedPL"],
                "Short Units":
                response["positions"][i]["short"]["units"],
                "Total Short P/L":
                response["positions"][i]["short"]["pl"],
                "Short Unrealized P/L":
                response["positions"][i]["short"]["unrealizedPL"],
            })

        df = pd.DataFrame.from_dict(position_data)
        print(df.to_string(index=False))
        print("")

    except V20Error as e:
        # pylint: disable=W0123
        d_error = eval(e.msg)
        print(d_error["errorMessage"], "\n")
예제 #22
0
    def get_positions(self):
        r = positions.OpenPositions(accountID=self.account_id)
        self.client.request(r)

        all_positions = r.response.get("positions", [])
        for position in all_positions:
            instrument = position['instrument']
            unrealized_pnl = position['unrealizedPL']
            pnl = position['pl']
            long = position['long']
            short = position['short']

            if short['units']:
                self.on_position_event(instrument, False, short['units'],
                                       unrealized_pnl, pnl)
            elif long['units']:
                self.on_position_event(instrument, True, long['units'],
                                       unrealized_pnl, pnl)
            else:
                self.on_position_event(instrument, None, 0, unrealized_pnl,
                                       pnl)
        return all_positions
예제 #23
0
    def get_position(self):

        req_position = positions.OpenPositions(accountID=self.account_id)

        self.client.request(req_position)

        resp_position = req_position.response

        if resp_position['positions'] == []:

            return {'side': 'buy', 'units': 0, 'price': None}

        else:
            in_position_list = False
            for pos in resp_position['positions']:

                if pos['instrument'] == self.ccy:
                    in_position_list = True
                    net_position = int(pos['short']['units']) + int(
                        pos['long']['units'])

                    if net_position > 0:
                        return {
                            'side': 'buy',
                            'units': abs(net_position),
                            'price': float(pos['long']['averagePrice'])
                        }

                    elif net_position < 0:
                        return {
                            'side': 'sell',
                            'units': abs(net_position),
                            'price': float(pos['short']['averagePrice'])
                        }

            if in_position_list == False:

                return {'side': 'buy', 'units': 0, 'price': None}
예제 #24
0
    def syncTrades(self):
        # load our pickled data structures
        self.load_data_structures()
        logger.info("   < local open positions: %s", str(self.open_positions))

        r = positions.OpenPositions(accountID=self.accountID)

        try:
            info = {}
            info = self.client.request(r)

            # if there are not open positins on oanda
            if len(info['positions']) == 0:
                self.open_positions = {}
                self.prediction = {}
                self.save()

            for pos in info['positions']:

                trade_ids = pos['long']['tradeIDs']
                for ID in trade_ids:
                    id = int(ID)
                    if id not in self.open_positions:

                        logger.warning("   < ID not in local positions: %s",
                                       str(ID))
                        logger.warning(
                            "   < Error: need to update open_positions")
                        logger.info("%s", str(self.open_positions))

                        # read from backup
                        self.read_from_backup(ID)

        except V20Error as e:
            logger.error("V20Error: %s", e)
            raise Exception("could not sync trades to api information")
예제 #25
0
 def request(self):
     open_position = positions.OpenPositions(self.account_id)
     return self.client.request(open_position)
예제 #26
0
파일: OandaAPI.py 프로젝트: zbanga/MLinc
# ############### Get Order Detail ################
#
# for order in trade_ids:
#     r = orders.OrderDetails(accountID=account_id, orderID=order['id'])
#     api.request(r)
#     print(r.response)
#
# ########### Get Pending Orders #############
#
# r = orders.OrdersPending(accountID=account_id)
# api.request(r)
# print(r.response)
#
########### Get all open positions ############

r = positions.OpenPositions(accountID=account_id)
api.request(r)
print(r.response)
all_positions = r.response['positions']
#
# ########## Closing an open position ###########
#
# instrument = "EUR_USD"
# data = {
#         "logUnits": "10",
#         "longClientExtensions": "Close 10 units of long positions in {}".format(instrument)
#         }
# r = positions.PositionClose(accountID=account_id,
#                             instrument=instrument,
#                             data=data)
# api.request(r)
예제 #27
0
def main():
    r = orders.OrderList(accountID=ACCOUNT_ID)
    open_orders = api.request(r)['orders']
    for order in open_orders:
        r = orders.OrderCancel(accountID=ACCOUNT_ID, orderID=order['id'])
        api.request(r)

    r = positions.OpenPositions(accountID=ACCOUNT_ID)
    open_positions = api.request(r)['positions']

    for pair in pairs:
        try:
            l_s, entry_price, amt_owned = get_position_details(
                open_positions, pair)
            if l_s != '':
                print('\n', pair, l_s)
                logging.error(f'\n--- {pair} {l_s} ---')
            df = create_df(pair)
            if l_s != '':
                print(df.tail())
                logging.error(f'\n{df.tail()}')
            signal = trade_signal(pair, df, l_s, entry_price)
            if l_s != '':
                print(f'signal: {signal}')
                logging.error(f'signal: {signal}')

            if (signal == 'buy'
                    or signal == 'sell') and len(open_positions) < max_trades:
                payload = {
                    'order': {
                        'type': 'LIMIT',
                        'instrument': pair,
                        'units': calculate_qty(df, signal, pair),
                        'price': calculate_price(df, pair, signal),
                        'TimeInForce': 'GTC',
                    }
                }
                r = orders.OrderCreate(accountID=ACCOUNT_ID, data=payload)
                api.request(r)
                print(
                    f'\nNew {signal} position initiated for {pair} \n***************************************\n'
                )
                logging.error(
                    f'\nNew {signal} position initiated for {pair} \n***************************************\n'
                )

            elif signal == 'close':
                r = trades.OpenTrades(accountID=ACCOUNT_ID)
                open_trades = api.request(r)['trades']
                for trade in open_trades:
                    if trade['instrument'] == pair:
                        r = trades.TradeClose(accountID=ACCOUNT_ID,
                                              tradeID=trade['id'])
                        api.request(r)
                print(
                    f'\nAll positions closed for {pair} \n***************************************\n'
                )
                logging.error(
                    f'\nAll positions closed for {pair} \n***************************************\n'
                )
        except:
            print(f'error encountered... skipping {pair}')
            logging.error(f'error encountered... skipping {pair}')
예제 #28
0
 def check_open_positions(self):
     r = positions.OpenPositions(self.accountID)
     return self.send_request(r)
예제 #29
0
def CAD():
    ACCESS_TOKEN = "YOUR OANDA API TOKEN"
    ACCOUNT_ID = "YOUR ACCOUNT ID"
    api = oandapyV20.API(access_token=ACCESS_TOKEN)
    close_prices = []
    open_prices = []
    low_prices = []
    high_prices = []
    volume_numbers = []
    list_of_time = []
    candleopen = []
    candleclose = []
    candlehigh = []
    candlelow = []
    candlevolume = []

    list_shortsl = []
    list_longsl = []

    quantity = 7500
    long_regulation_trade = [
        quantity, quantity + 500, quantity + 1000, quantity + 2000,
        quantity + 4000
    ]
    long_regulation_number = 0
    short_regulation_trade = [
        quantity, quantity + 500, quantity + 1000, quantity + 2000,
        quantity + 4000
    ]
    short_regulation_number = 0
    while True:
        params = {"count": 7, "granularity": "M2"}

        instrum = instruments.InstrumentsCandles(instrument="USD_CAD",
                                                 params=params)
        json_response = api.request(instrum)
        for candlenum in range(len(json_response["candles"])):
            openprice = float(json_response["candles"][candlenum]['mid']['o'])
            closeprice = float(json_response["candles"][candlenum]['mid']['c'])
            highprice = float(json_response["candles"][candlenum]['mid']['h'])
            lowprice = float(json_response["candles"][candlenum]['mid']['l'])
            volume = float(json_response["candles"][candlenum]['volume'])

            timestamped = (json_response["candles"][candlenum]['time'])

            if timestamped not in list_of_time:
                list_of_time.append(timestamped)
                if len(candleopen) >= 1:
                    close_prices.append(candleclose[-1])
                    open_prices.append(candleopen[-1])
                    low_prices.append(candlelow[-1])
                    high_prices.append(candlehigh[-1])
                    volume_numbers.append(candlevolume[-1])
                    #reset candles
                    candleopen = []
                    candleclose = []
                    candlehigh = []
                    candlelow = []
                    candlevolume = []

                    if len(close_prices) > 7:
                        #Pricing info- bid and ask
                        query = {"instruments": "USD_CAD"}
                        pricingrequest = pricing.PricingInfo(
                            accountID=ACCOUNT_ID, params=query)
                        recievedrequest = api.request(pricingrequest)
                        bidprice = pricingrequest.response['prices'][0][
                            'bids'][0]['price']
                        askprice = pricingrequest.response['prices'][0][
                            'asks'][0]['price']

                        shorttp = round(float(bidprice) * 1.0058, 6)
                        shortsl = round(float(askprice) * 0.9988, 6)
                        longtp = round(float(bidprice) * 0.9942, 6)
                        longsl = round(float(askprice) * 1.0012, 6)

                        #Account info- open positions
                        account_details = positions.OpenPositions(
                            accountID=ACCOUNT_ID)
                        api.request(account_details)

                        #Market order creation- short position
                        shortmktOrder = MarketOrderRequest(
                            instrument="USD_CAD",
                            units=-(
                                short_regulation_trade[short_regulation_number]
                            ),
                            takeProfitOnFill=TakeProfitDetails(
                                price=shorttp).data,
                            stopLossOnFill=StopLossDetails(price=shortsl).data)
                        shortordercreation = orders.OrderCreate(
                            ACCOUNT_ID, data=shortmktOrder.data)

                        #Market order creation- long position
                        longmktOrder = MarketOrderRequest(
                            instrument="USD_CAD",
                            units=(
                                long_regulation_trade[long_regulation_number]),
                            takeProfitOnFill=TakeProfitDetails(
                                price=longtp).data,
                            stopLossOnFill=StopLossDetails(price=longsl).data)
                        longordercreation = orders.OrderCreate(
                            ACCOUNT_ID, data=longmktOrder.data)

                        numclose = np.array(close_prices)
                        numopen = np.array(open_prices)
                        numlow = np.array(low_prices)
                        numhigh = np.array(high_prices)
                        numvolume = np.array(volume_numbers)

                        rsii = talib.RSI(numclose, 7)
                        mfi = talib.MFI(numhigh, numlow, numclose, numvolume,
                                        7)
                        atr = talib.ATR(numhigh, numlow, numclose, 7)

                        print("USD_CAD: The current MFI is {}.".format(
                            mfi[-1]))
                        print("USD_CAD: The current RSI is {}.".format(
                            rsii[-1]))
                        print("USD_CAD: The current ATR is {}.".format(
                            atr[-1]))
                        print(
                            "------------------------------------------------------------------------------------------------------------------------"
                        )
                        if float(bidprice) / float(askprice) >= 0.99985:
                            if short_regulation_number == 6:
                                pass
                            else:
                                if rsii[-1] >= 75 and rsii[-2] >= 75 and rsii[
                                        -3] >= 75 and atr[-1] <= 0.00035:

                                    list_shortsl.append(shortsl)
                                    try:
                                        # create the OrderCreate request
                                        rv = api.request(shortordercreation)
                                    except oandapyV20.exceptions.V20Error as err:
                                        print(shortordercreation.status_code,
                                              err)
                                    else:
                                        print(
                                            'USD_CAD: Short order for {} units created at {}'
                                            .format(
                                                short_regulation_trade[
                                                    short_regulation_number],
                                                askprice))
                                        short_regulation_number += 1

                            if long_regulation_number == 6:
                                pass
                            else:
                                if rsii[-1] <= 25 and rsii[-2] <= 25 and rsii[
                                        -3] <= 25 and atr[-1] <= 0.00035:

                                    list_longsl.append(longsl)
                                    try:
                                        # create the OrderCreate request
                                        rv = api.request(longordercreation)
                                    except oandapyV20.exceptions.V20Error as err:
                                        print(longordercreation.status_code,
                                              err)
                                    else:
                                        print(
                                            'USD_CAD: Long for {} units created at {}'
                                            .format(
                                                long_regulation_trade[
                                                    long_regulation_number],
                                                bidprice))
                                        long_regulation_number += 1

                        else:
                            print("Bid/ask too wide for entry.")

                            if mfi[-1] <= 10:
                                for i in range(
                                        len(account_details.
                                            response['positions'])):
                                    try:
                                        if account_details.response[
                                                'positions'][i][
                                                    'instrument'] == 'USD_CAD':
                                            if float(account_details.
                                                     response['positions'][i]
                                                     ['short']['units']) < 0:
                                                units_available = int(
                                                    account_details.
                                                    response['positions'][i]
                                                    ['short']['units'])

                                                mktOrder = MarketOrderRequest(
                                                    instrument="USD_CAD",
                                                    units=-(units_available),
                                                )
                                                r = orders.OrderCreate(
                                                    ACCOUNT_ID,
                                                    data=longmktOrder.data)
                                                try:
                                                    # create the OrderCreate request
                                                    rv = api.request(r)
                                                except oandapyV20.exceptions.V20Error as err:
                                                    print(r.status_code, err)
                                                else:
                                                    print(
                                                        'USD_CAD: Cover short for {} units created at {}'
                                                        .format(
                                                            units_available,
                                                            askprice))
                                                    short_regulation_number = 0
                                    except IndexError:
                                        pass
                                    except KeyError:
                                        pass

                            if mfi[-1] >= 90:
                                for i in range(
                                        len(account_details.
                                            response['positions'])):
                                    try:
                                        if account_details.response[
                                                'positions'][i][
                                                    'instrument'] == 'USD_CAD':
                                            if float(account_details.
                                                     response['positions'][i]
                                                     ['long']['units']) > 0:
                                                units_available = int(
                                                    account_details.
                                                    response['positions'][i]
                                                    ['long']['units'])

                                                mktOrder = MarketOrderRequest(
                                                    instrument="USD_CAD",
                                                    units=-(units_available),
                                                )
                                                r = orders.OrderCreate(
                                                    ACCOUNT_ID,
                                                    data=mktOrder.data)
                                                try:
                                                    # create the OrderCreate request
                                                    rv = api.request(r)
                                                except oandapyV20.exceptions.V20Error as err:
                                                    print(r.status_code, err)
                                                else:
                                                    print(
                                                        'USD_CAD: Selling off {} long units created at {}'
                                                        .format(
                                                            units_available,
                                                            bidprice))
                                                    long_regulation_number = 0
                                    except IndexError:
                                        pass
                                    except KeyError:
                                        pass

            else:
                candleopen.append(openprice)
                candleclose.append(closeprice)
                candlelow.append(lowprice)
                candlehigh.append(highprice)
                candlevolume.append(volume)
예제 #30
0
def main():
    print "------ System online -------", datetime.now()

    parser = argparse.ArgumentParser()

    common.config.add_argument(parser)

    parser.add_argument('--instrument',
                        "-i",
                        type=common.args.instrument,
                        required=True,
                        action="append",
                        help="Instrument to get prices for")

    parser.add_argument('--snapshot',
                        action="store_true",
                        default=True,
                        help="Request an initial snapshot")

    parser.add_argument('--no-snapshot',
                        dest="snapshot",
                        action="store_false",
                        help="Do not request an initial snapshot")

    parser.add_argument('--show-heartbeats',
                        "-s",
                        action='store_true',
                        default=False,
                        help="display heartbeats")

    args = parser.parse_args()
    #print sys.argv[2]
    account_id = args.config.active_account
    api = args.config.create_streaming_context()
    account_api = args.config.create_context()

    response = api.pricing.stream(account_id,
                                  snapshot=args.snapshot,
                                  instruments=",".join(args.instrument))

    p = PivotImports(sys.argv[2], datetime.now().date())
    dfD = p.daily()
    #dfW = p.weekly()
    bal = Balance(account_api, account_id)
    balance = bal.balance()

    df = pd.DataFrame([])

    for msg_type, msg in response.parts():
        if msg_type == "pricing.Heartbeat" and args.show_heartbeats:
            print(heartbeat_to_string(msg))

        if msg_type == "pricing.Price":
            sd = StreamingData(datetime.now(), instrument_string(msg),
                               mid_string(msg), account_api, account_id, 's',
                               '1min', balance)
            df = df.append(sd.df())
            sd.resample(df)
            print "df:", df.shape[0], "minuteData:", sd.minuteData().shape[0]
            #print sd.minuteData(),'\n'

            if sd.minuteData().shape[0] < 20: continue

            else:
                client = oandapyV20.API(settings.ACCESS_TOKEN)
                r = openPos.OpenPositions(accountID=account_id)
                client.request(r)
                openTrades = []
                for i in r.response['positions']:
                    trades = i['instrument']
                    openTrades.append(trades)
                print 'Open Trades', openTrades

                if instrument_string(msg) in openTrades: continue

                else:
                    try:
                        b = Breakout(sd.minuteData(), mid_string(msg))
                        breakout = b.breakout()
                        #print 'Breakout Units:',breakout

                        s = Spreads(dfD, mid_string(msg))
                        pivot, rl1, rl2, rl3, sl1, sl2, sl3 = s.spreads()
                        rate1, rate2 = s.spreads_out()

                        strat = Strategy(account_api, account_id,
                                         instrument_string(msg), dfD,
                                         mid_string(msg), breakout, pivot, rl1,
                                         rl2, rl3, sl1, sl2, sl3, rate1, rate2)
                        strat.res_check()
                        strat.sup_check()

                    #except Exception as e: print(e)
                    except:
                        continue