Exemplo n.º 1
0
    def main(self):
        self.resistance = max(self.data[(uniVar.count - 6):uniVar.count])
        self.support = max(self.data[(uniVar.count - 6):uniVar.count])

        #oanda parameters
        mktOrderLong = MarketOrderRequest(
            instrument=uniVar.pair,
            units=self.lots(),
            takeProfitOnFill=TakeProfitDetails(price=self.resistance).data,
            stopLossOnFill=StopLossDetails(price=self.support).data)

        mktOrderShort = MarketOrderRequest(
            instrument=uniVar.pair,
            units=(self.lots() * -1),
            takeProfitOnFill=TakeProfitDetails(price=self.support).data,
            stopLossOnFill=StopLossDetails(price=self.resistance).data)

        #Trading conditions
        if self.getTrades() == 0:
            print("Looking for trades.")
            if self.enterLong() == True:
                api = oandapyV20.API(access_token=uniVar.key)
                r = orders.OrderCreate(uniVar.accountID,
                                       data=mktOrderLong.data)
                api.request(r)
                self.status == 'Currently Trading'
                self.currentTrade == 'Long'
                print('Trade Executed')

            elif self.enterShort() == True:
                api = oandapyV20.API(access_token=uniVar.key)
                r = orders.OrderCreate(uniVar.accountID,
                                       data=mktOrderShort.data)
                api.request(r)
                self.status == 'Currently Trading'
                self.currentTrade == 'Long'
                print('Trade Executed')

            elif self.enterLong() and self.enterShort() == False:
                print('No open trades, currently looking for one')

        else:
            if self.currentTrade == 'Short':
                if self.enterLong() == True:
                    self.closePosition()
                    self.status == 'Not Trading'
                    print('Short Trade exited')
                else:
                    print('No Short exits, currently looking for one')
            elif self.currentTrade == 'Long':
                if self.enterShort() == True:
                    self.closePosition()
                    self.status == 'Not Trading'
                    print('Long Trade exited')
                else:
                    print('No Long exits, currently looking for one')
            else:
                self.kill = True
                print('Kill switch initiated, closing down')
Exemplo n.º 2
0
    def main(self):
        self.resistance = max(self.data[(userVals.count - 6):userVals.count])
        self.support = min(self.data[(userVals.count - 6):userVals.count])

        # Oanda Parameters
        mktOrderLong = MarketOrderRequest(
            instrument=userVals.pair,
            units=self.lots(),
            takeProfitOnFill=TakeProfitDetails(price=self.resistance).data,
            stopLossOnFill=StopLossDetails(price=self.support).data)
        mktOrderShort = MarketOrderRequest(
            instrument=userVals.pair,
            units=(self.lots() * -1),
            takeProfitOnFill=TakeProfitDetails(price=self.support).data,
            stopLossOnFill=StopLossDetails(price=self.resistance).data)

        # Trading Conditions
        if self.getTrades() == 0:
            print "Looking for trades."
            if self.enterLong() == True:
                api = oandapyV20.API(access_token=userVals.key)
                r = orders.OrderCreate(userVals.accountID,
                                       data=mktOrderLong.data)
                api.request(r)
                self.status == "Trading"
                self.currentTrade == "Long"
                print "Trade Executed"

            elif self.enterShort() == True:
                api = oandapyV20.API(access_token=userVals.key)
                r = orders.OrderCreate(userVals.accountID,
                                       data=mktOrderShort.data)
                api.request(r)
                self.status == "Trading"
                self.currentTrade == "Short"
                print "Trade Executed"

            elif self.enterLong() and self.enterShort() == False:
                print "No Trades Open, Looking for Entry..."
        else:
            if self.currentTrade == "Short":
                if self.enterLong() == True:
                    self.closePosition()
                    self.status == "Not Trading"
                    print "Trade Exited"
                else:
                    print "No exits.. Looking"
            elif self.currentTrade == "Long":
                if self.enterShort() == True:
                    self.closePosition()
                    self.status == "Not Trading"
                    print "Trade Exited"
                else:
                    print "No exits.. Looking"
            else:
                self.kill = True
                print "Error, Closing down."
Exemplo n.º 3
0
    def order(self, instrument, weight, price):
        # calculate TP/SL, these are fixed @ .5%/.25%; change to fit your needs
        p = str(price)
        p = p.split('.')
        p = len(p[1])
        self.TP_long = round((price * 1.005), p)
        self.SL_long = round((price * 0.9975), p)
        self.TP_short = round((price * 0.995), p)
        self.SL_short = round(
            (price * 1.0025),
            p)  # sometimes have an issue rounding with JPY crosses

        if self.weight > 0:
            mktOrder = MarketOrderRequest(
                instrument=instrument,
                units=weight,
                TakeProfitOnFill=TakeProfitDetails(price=self.TP_long).data,
                stopLossOnFill=StopLossDetails(price=self.SL_long).data)
            r = orders.OrderCreate(accountID, data=mktOrder.data)

            try:
                rv = self.api.request(r)
                if self.should_print == True:
                    print(r.status_code)
            except V20Error as e:
                print(r.status_code, e)
            else:
                if self.should_print == True:
                    print(json.dumps(rv, indent=4))

        else:
            mktOrder = MarketOrderRequest(
                instrument=instrument,
                units=weight,
                TakeProfitOnFill=TakeProfitDetails(price=self.TP_short).data,
                stopLossOnFill=StopLossDetails(price=self.SL_short).data)
            r = orders.OrderCreate(accountId, data=mktOrder.data)

            try:
                rv = self.api.request(r)
                if self.should_print == True:
                    print(r.status_code)
            except V20Error as e:
                print(r.status_code, e)
            else:
                if self.should_print == True:
                    print(json.dumps(rv, indent=4))

        return r.response
def order_buy_calc(pair, atr):
    price = (df_h[pair].iloc[:, 4]).astype(float)[0]
    sl = price - (1 * (atr * 0.50))
    tp = price + (1 * (atr * 0.50))

    # print("the price for", i, "is: ", price)
    # print("the tp for", i, "is: ", tp)
    # print("the sl for", i, "is: ", sl)

    takeProfitOnFillOrder = TakeProfitDetails(price=tp)
    StopLossOnFillOrder = StopLossDetails(price=sl)

    print(takeProfitOnFillOrder.data)
    print(StopLossOnFillOrder.data)

    # requests.post(url, data=order_b)

    order_buy = MarketOrderRequest(instrument=pair,
                                   units=1,
                                   takeProfitOnFill=takeProfitOnFillOrder.data,
                                   stopLossOnFill=StopLossOnFillOrder.data)

    r = orders.OrderCreate(accountID, data=order_buy.data)
    print("Processing : {}".format(r))
    print("====================")
    print(r.data)

    try:
        response = api.request(r)
    except V20Error as e:
        print("V20Error:{}".format(e))
    else:
        print("Respose: {}\n{}".format(r.status_code,
                                       json.dumps(response, indent=2)))
Exemplo n.º 5
0
    def order(self, units):
        mop = {"instrument": self.pt.instrument, "units": units}

        def frmt(v):
            # format a number over 6 digits: 12004.1, 1.05455
            l = len(str(v).split(".")[0])
            return "{{:{}.{}f}}".format(l, 6 - l).format(v)

        direction = 1 if units > 0 else -1
        if self.clargs.takeProfit:  # takeProfit specified? add it
            tpPrice = self.pt._c[self.pt.idx-1] * \
                      (1.0 + (self.clargs.takeProfit/100.0) * direction)
            mop.update({
                "takeProfitOnFill":
                TakeProfitDetails(price=frmt(tpPrice)).data
            })

        if self.clargs.stopLoss:  # stopLosss specified? add it
            slPrice = self.pt._c[self.pt.idx-1] * \
                      (1.0 + (self.clargs.stopLoss/100.0) * -direction)
            mop.update(
                {"stopLossOnFill": StopLossDetails(price=frmt(slPrice)).data})

        data = MarketOrderRequest(**mop).data
        r = orders.OrderCreate(accountID=self.accountID, data=data)
        try:
            response = self.client.request(r)
        except V20Error as e:
            logger.error("V20Error: %s", e)
        else:
            logger.info("Response: %d %s", r.status_code,
                        json.dumps(response, indent=2))
Exemplo n.º 6
0
    def OrderCreate_pending(self, ticker, size, price, takeprofit=None,
                            stoploss=None, trailingstop=None,
                            requesttype='MarketIfTouchedOrder'):
        
        d = dict(instrument=ticker, units=size, price=price)

        if takeprofit:
            d['takeProfitOnFill'] = TakeProfitDetails(price=takeprofit).data

        if stoploss:
            d['stopLossOnFill'] = StopLossDetails(price=stoploss).data

        if trailingstop:
            d['trailingStopLossOnFill'] = TrailingStopLossDetails(
                distance=trailingstop).data

        if requesttype is 'MarketIfTouchedOrder':
            Order = MITOrderRequest(**d).data
        elif requesttype is 'LimitOrder':
            Order = LimitOrderRequest(**d).data
        elif requesttype is 'StopOrder':
            Order = StopOrderRequest(**d).data

        r = orders.OrderCreate(accountID=self.accountID, data=Order)

        return self.client.request(r)
def order_buy_calc(pair, atr):
    price = (df_h[pair].iloc[:, 4]).astype(float)[0]
    sl = price - (1 * (atr * 0.50))
    tp = price + (1 * (atr * 0.50))

    # print("the price for", i, "is: ", price)
    # print("the tp for", i, "is: ", tp)
    # print("the sl for", i, "is: ", sl)

    takeProfitOnFillOrder = TakeProfitDetails(price=tp)
    StopLossOnFillOrder = StopLossDetails(price=sl)

    print(takeProfitOnFillOrder.data)
    print(StopLossOnFillOrder.data)

    #############
    #############
    #############          CHECK ORDER  BELOW ....
    #############
    #############

    # requests.post(url, data=order_b)

    ordr = MarketOrderRequest(instrument=pair,
                              units=1,
                              takeProfitOnFill=takeProfitOnFillOrder.data,
                              stopLossOnFill=StopLossOnFillOrder.data)
    order_buy = json.dumps(ordr.data, indent=4)

    requestdata = requests.post(url=url, data=order_buy)
Exemplo n.º 8
0
    def OrderCreate_mkt(self,
                        ticker,
                        size,
                        takeprofit=None,
                        stoploss=None,
                        trailingstop=None):
        """
        建立市价单
        requesttype:
                MarketOrder
        """
        d = dict(instrument=ticker, units=size)

        if takeprofit:
            d['takeProfitOnFill'] = TakeProfitDetails(price=takeprofit).data

        if stoploss:
            d['stopLossOnFill'] = StopLossDetails(price=stoploss).data

        if trailingstop:
            d['trailingStopLossOnFill'] = TrailingStopLossDetails(
                distance=trailingstop).data

        Order = MarketOrderRequest(**d).data

        r = orders.OrderCreate(accountID=self.accountID, data=Order)

        return self.client.request(r)
Exemplo n.º 9
0
def order_sell_calc(pair, atr):
    price = (df_h[pair].iloc[:, 4]).astype(float)[0]
    sl = price - (1 * (atr * 0.50))
    tp = price + (1 * (atr * 0.50))

    takeProfitOnFillOrder = TakeProfitDetails(price=tp)
    StopLossOnFillOrder = StopLossDetails(price=sl)

    order_sell = MarketOrderRequest(
        instrument=pair,
        units=-10,
        takeProfitOnFill=takeProfitOnFillOrder.data,
        stopLossOnFill=StopLossOnFillOrder.data)

    r = orders.OrderCreate(accountID, data=order_sell.data)
    print("Processing selling order of : {}".format(r))
    print("====================")
    print(r.data)

    try:
        response = api.request(r)
    except V20Error as e:
        print("V20Error:{}".format(e))
    else:
        print("Respose: {}\n{}".format(r.status_code,
                                       json.dumps(response, indent=2)))
Exemplo n.º 10
0
 def place_market_order(self, instrument: str, side: str, units: Union[float, int], tp: float = None, sl: float = None):
     order_request = MarketOrderRequest(
         instrument=instrument,
         units=units * (1 if side == OrderSide.LONG else -1),
         takeProfitOnFill=TakeProfitDetails(price=self._adjust_decimals(instrument, tp)).data if tp else None,
         stopLossOnFill=StopLossDetails(price=self._adjust_decimals(instrument, sl)).data if sl else None,
     )
     self._submit_order_request(order_request, self.account_id)
Exemplo n.º 11
0
 def market_order_short_sl_tp(self, sl, tp, pair="AUD_USD", unit=-1000):
     client = API(access_token=self.access_token, environment='live')
     stopLossOnFill = StopLossDetails(price=sl)
     takeProfitOnFillOrder = TakeProfitDetails(price=tp)
     ordr = MarketOrderRequest(instrument=pair,
                               units=unit,
                               stopLossOnFill=stopLossOnFill.data,
                               takeProfitOnFill=takeProfitOnFillOrder.data)
     r = orders.OrderCreate(self.accountID, data=ordr.data)
     rv = client.request(r)
Exemplo n.º 12
0
 def place_stop_order(self, instrument: str, side: str, units: Union[float, int], price: float, tp: float, sl: float, expiry: str = None):
     order_request = StopOrderRequest(
         instrument=instrument,
         units=units * (1 if side == OrderSide.LONG else -1),
         price=self._adjust_decimals(instrument, price),
         takeProfitOnFill=TakeProfitDetails(price=self._adjust_decimals(instrument, tp)).data,
         stopLossOnFill=StopLossDetails(price=self._adjust_decimals(instrument, sl)).data,
         timeInForce='GTD' if expiry else 'GTC',
         gtdTime=expiry
     )
     self._submit_order_request(order_request, self.account_id)
Exemplo n.º 13
0
 def OrderCreate_mkt(self,
                     instrument,
                     units,
                     takeProfit_price=None,
                     stopLoss_price=None):
     mktOrder = MarketOrderRequest(
         instrument=instrument,
         units=units,
         takeProfitOnFill=TakeProfitDetails(price=takeProfit_price).data,
         stopLossOnFill=StopLossDetails(price=stopLoss_price).data).data
     r = orders.OrderCreate(accountID=self.accountID, data=mktOrder)
     return self.client.request(r)
Exemplo n.º 14
0
    def order(self, symbol, size, target, stop, type='mkt'):

        mktOrderLong = MarketOrderRequest(
            symbol,
            units=size,
            takeProfitOnFill=TakeProfitDetails(price=target).data,
            stopLossOnFill=StopLossDetails(price=stop).data)

        lmtOrderLong = LimitOrderRequest(
            symbol,
            units=size,
            price=round(target * 1.05, self.account_instruments(symbol)),
            takeProfitOnFill=TakeProfitDetails(price=target).data,
            stopLossOnFill=StopLossDetails(price=stop).data)

        if type == 'lmt':
            r = orders.OrderCreate(ACCOUNT_ID, lmtOrderLong.data)
        else:
            r = orders.OrderCreate(ACCOUNT_ID, mktOrderLong.data)

        data = api.request(r)

        return data
Exemplo n.º 15
0
    def execute(self, params):
        instrument = params['instrument']
        take_profit = params['take_profit']
        stop_loss = params['stop_loss']
        units = params['units']

        mktOrder = MarketOrderRequest(
            instrument=instrument,
            units=units,
            takeProfitOnFill=TakeProfitDetails(price=take_profit).data,
            stopLossOnFill=StopLossDetails(price=stop_loss).data)

        response = orders.OrderCreate(self.account_id, data=mktOrder.data)
        return self.client.request(response)
Exemplo n.º 16
0
def order(instrument, weight, price, TP, SL):

    if weight > 0:
        mktOrder = MarketOrderRequest(
                        instrument=instrument,
                        units=weight,
                        takeProfitOnFill=TakeProfitDetails(price=TP).data,
                        stopLossOnFill=StopLossDetails(price=SL).data)
        r = orders.OrderCreate(accountID, data=mktOrder.data)

        try:
            rv = api.request(r)
            #print(r.status_code)
        except V20Error as e:
            print(r.status_code, e)
        else:
            #print(json.dumps(rv, indent=4))
            pass

    else:
        mktOrder = MarketOrderRequest(
                            instrument=instrument,
                            units=weight,
                            takeProfitOnFill=TakeProfitDetails(price=TP).data,
                            stopLossOnFill=StopLossDetails(price=SL).data)
        r = orders.OrderCreate(accountID, data=mktOrder.data)

        try:
            rv = api.request(r)
            #print(r.status_code)
        except V20Error as e:
            print(r.status_code, e)
        else:
            #print(json.dumps(rv, indent=4))
            pass

    return r.response
Exemplo n.º 17
0
def create_order(limit,loss, units):
    mktOrder = MarketOrderRequest(
        instrument = instrument,
        units = units,
        takeProfitOnFill = TakeProfitDetails(price=limit).data,
        trailingStopLossOnFill=TrailingStopLossDetails(distance=loss,timeInForce='GTC').data,
            )
    r = orders.OrderCreate(acccount_id,data=mktOrder.data)
    try:
        rv = api.request(r)
    except oandapyV20.exceptions.V20Error as err:
        print(r.status_code, err)
    else:
        #print(rv)
        return int(rv["relatedTransactionIDs"][1])
Exemplo n.º 18
0
def do_short(bid):
    if config.take_profit_value != 0 or config.stop_loss_value != 0:
        order = MarketOrderRequest(
            instrument=config.insName,
            units=-config.lot_size,
            takeProfitOnFill=TakeProfitDetails(price=bid +
                                               config.take_profit_value).data,
            stopLossOnFill=StopLossDetails(price=bid -
                                           config.stop_loss_value).data)
    else:
        order = MarketOrderRequest(instrument=config.insName,
                                   units=-config.lot_size)
    r = orders.OrderCreate(config.account_id, data=order.data)
    resp = oanda.request(r)
    print(resp)
    price = resp.get('orderFillTransaction').get('price')
    print(time, 's: SELL price =', price)
    return float(price)
Exemplo n.º 19
0
    def __init__(self, instr, units, take_profit, stop_loss):
        access_token = config['account']['token']
        accountID = config['account']['accountID']
        api = API(access_token=access_token)

        mktOrder = MarketOrderRequest(
            instrument=instr,
            units=units,
            takeProfitOnFill=TakeProfitDetails(price=take_profit).data,
            stopLossOnFill=StopLossDetails(price=stop_loss).data)

        r = orders.OrderCreate(accountID, data=mktOrder.data)
        try:
            rv = api.request(r)
        except oandapyV20.exceptions.V20Error as err:
            print(r.status_code, err)
        else:
            print(json.dumps(rv, indent=2))
Exemplo n.º 20
0
    def _place_order(self,
                     _type='market',
                     units=1000,
                     side='LONG',
                     instrument='EUR_USD',
                     price=None,
                     stop_loss=None,
                     take_profit=None):
        if take_profit:
            take_profit = TakeProfitDetails(price=take_profit).data

        if stop_loss:
            stop_loss = StopLossDetails(price=stop_loss).data

        if side == 'SHORT':
            units = -units

        if _type == 'market':
            mktOrder = MarketOrderRequest(instrument=instrument,
                                          units=units,
                                          takeProfitOnFill=take_profit,
                                          stopLossOnFill=stop_loss).data
            order = orders.OrderCreate(accountID=self.accountID, data=mktOrder)
        elif _type == 'stop':
            stopOrder = StopOrderRequest(instrument=instrument,
                                         units=units,
                                         price=price,
                                         takeProfitOnFill=take_profit,
                                         stopLossOnFill=stop_loss).data
            order = orders.OrderCreate(accountID=self.accountID,
                                       data=stopOrder)
        elif _type == 'limit':
            limitOrder = LimitOrderRequest(instrument=instrument,
                                           units=units,
                                           price=price,
                                           takeProfitOnFill=take_profit,
                                           stopLossOnFill=stop_loss).data
            order = orders.OrderCreate(accountID=self.accountID,
                                       data=limitOrder)

        return self.client.request(order)
Exemplo n.º 21
0
    def send_market_order(self,
                          instrument,
                          quantity,
                          is_buy,
                          take_profit=None,
                          stop_loss=None):

        tp = None if take_profit is None else TakeProfitDetails(
            price=take_profit).data

        sl = None if stop_loss is None else StopLossDetails(
            price=stop_loss).data

        if is_buy:
            mkt_order = MarketOrderRequest(instrument=instrument,
                                           units=quantity,
                                           takeProfitOnFill=tp,
                                           stopLossOnFill=sl)
        else:
            mkt_order = MarketOrderRequest(instrument=instrument,
                                           units=(quantity * -1),
                                           takeProfitOnFill=tp,
                                           stopLossOnFill=sl)

        r = orders.OrderCreate(self.account_id, data=mkt_order.data)
        self.client.request(r)

        if r.status_code != 201:
            self.on_order_event(instrument, quantity, is_buy, None,
                                'NOT_FILLED')
            return False

        if 'orderCancelTransaction' in r.response:
            self.on_order_event(instrument, quantity, is_buy, None,
                                'NOT_FILLED')
            return False

        transaction_id = r.response.get('lastTransactionID', None)
        self.on_order_event(instrument, quantity, is_buy, transaction_id,
                            'FILLED')
        return r
Exemplo n.º 22
0
 def createMarketOrder(self, instrument, units, 
                 takeprofit_price=0, stoploss_price=0):
     if takeprofit_price == 0:
         tp_details = None
     else:
         tp_details = TakeProfitDetails(price=takeprofit_price).data
 
     if stoploss_price == 0:
         sl_details = None
     else:
         sl_details = StopLossDetails(price=stoploss_price).data
 
     mktOrder = MarketOrderRequest(
         instrument=instrument,
         units=units,
         takeProfitOnFill=tp_details,
         stopLossOnFill=sl_details
         )
     
     r = orders.OrderCreate(self.accountID, data=mktOrder.data)
     return self.request(r)
Exemplo n.º 23
0
def create_market_order(order_instrument, order_units, order_take_profit,
                        order_stop_loss):
    """ 
    Create a market order.
    A market order is an order that is filled immediately upon creation using the current market price.
    """
    # Create the order body
    ordr = MarketOrderRequest(
        instrument=order_instrument,
        units=order_units,
        takeProfitOnFill=TakeProfitDetails(price=order_take_profit).data,
        stopLossOnFill=StopLossDetails(price=order_stop_loss).data)
    # create the OrderCreate request
    r = orders.OrderCreate(accountID, data=ordr.data)
    try:
        # create the OrderCreate request
        rv = api.request(r)
    except oandapyV20.exceptions.V20Error as err:
        print(r.status_code, err)
    else:
        print(json.dumps(rv, indent=2))
Exemplo n.º 24
0
def openPosition(money, currency, stopLoss, takeProfit):
    """
    Creates a new buy order
    :param money: Amount to buy
    :param currency: Currency pair to buy
    :param stopLoss: Stop loss price
    :param takeProfit: Take profit price
    :return:
    """
    exchange = currency[:3] + "_" + currency[
        3:]  # Format the currency pair by removing the '_'
    stopLossOnFill = StopLossDetails(
        price=stopLoss)  # Stop loss and take profit details
    takeProfitOnFill = TakeProfitDetails(price=takeProfit)
    mo = MarketOrderRequest(
        instrument=exchange,
        units=money,
        stopLossOnFill=stopLossOnFill.data,
        takeProfitOnFill=takeProfitOnFill.data)  # exchange="EUR_USD"
    time_current = datetime.now(pytz.timezone('America/Chicago'))
    r = orders.OrderCreate(accountID, data=mo.data)  # Create the order request
    rv = api.request(r)  # perform the request
Exemplo n.º 25
0
def placing_order(order_type, instrument, side, units, price, tp, sl):
    """
    Placing order
    :param order_type:
            "MARKET": "A Market Order",
            "LIMIT": "A Limit Order",
            "STOP": "A Stop Order",
            "MARKET_IF_TOUCHED": "A Market-if-touched Order",
            "TAKE_PROFIT": "A Take Profit Order",
            "STOP_LOSS": "A Stop Loss Order",
            "TRAILING_STOP_LOSS": "A Trailing Stop Loss Order",
            "FIXED_PRICE": "A Fixed Price Order"
    :param instrument: A string containing the base currency and quote currency delimited by a “_”.
    :param side: long/buy or short/sell
    :param units: units size
    :param price: price
    :param tp: take profit
    :param sl: stop loss
    :return:
    """
    if order_type == OrderType.STOP:
        order_request = StopOrderRequest(
            instrument=instrument,
            units=units if side == 'buy' else units * -1,
            price=price,
            takeProfitOnFill=TakeProfitDetails(price=tp).data,
            stopLossOnFill=StopLossDetails(price=sl).data)
    else:
        raise NotImplemented(f'{order_type} is not supported yet')

    print(json.dumps(order_request.data, indent=4))
    r = orders.OrderCreate(RUNNING_ENV.account.mt4, data=order_request.data)
    try:
        # create the OrderCreate request
        rv = RUNNING_ENV.api.request(r)
    except V20Error as err:
        logging.error(r.status_code, err)
    else:
        logging.info(json.dumps(rv, indent=2))
Exemplo n.º 26
0
def create_limit_order(order_instrument, order_units, order_take_profit,
                       order_stop_loss, order_price):
    """ 
    Create a limit order.
    The Limit Order will only be filled by a market price that is equal to or better than this price.
    """
    # Create the order body
    ordr = LimitOrderRequest(
        instrument=order_instrument,
        units=order_units,
        takeProfitOnFill=TakeProfitDetails(price=order_take_profit).data,
        stopLossOnFill=StopLossDetails(price=order_stop_loss).data,
        price=order_price)
    # create the OrderCreate request
    r = orders.OrderCreate(accountID, data=ordr.data)
    try:
        # create the OrderCreate request
        rv = api.request(r)
    except oandapyV20.exceptions.V20Error as err:
        print(r.status_code, err)
    else:
        print(json.dumps(rv, indent=2))
Exemplo n.º 27
0
def create_stop_order(order_instrument, order_units, order_take_profit,
                      order_stop_loss, order_price):
    """ 
    Create a stop order.
    A StopOrder is an order that is created with a price threshold, 
    and will only be filled by a price that is equal to or worse 
    than the threshold.
    """
    # Create the order body
    ordr = StopOrderRequest(
        instrument=order_instrument,
        units=order_units,
        takeProfitOnFill=TakeProfitDetails(price=order_take_profit).data,
        stopLossOnFill=StopLossDetails(price=order_stop_loss).data,
        price=order_price)
    # create the OrderCreate request
    r = orders.OrderCreate(accountID, data=ordr.data)
    try:
        # create the OrderCreate request
        rv = api.request(r)
    except oandapyV20.exceptions.V20Error as err:
        print(r.status_code, err)
    else:
        print(json.dumps(rv, indent=2))
Exemplo n.º 28
0
    def _open_position(self, pos_type: int, funds_alloc: float = 1):
        # Buy as many units as possible using a funds_alloc fraction of the
        # total funds assigned to this trader with a stop loss at the range low
        price = self.ask if pos_type == POS_LONG else self.bid
        stop_loss = self.low if pos_type == POS_LONG else self.high
        take_profit = price*(1 + pos_type*DESIRED_MARGIN)
        order = MarketOrderRequest(
            instrument = self.instrument,
            units = pos_type*funds_alloc*self.funds/price,
            stopLossOnFill = StopLossDetails(stop_loss).data,
            takeProfitOnFill = TakeProfitDetails(take_profit).data,
        )

        # Assemble the request and send it
        logging.info(f'Placing order for {self.instrument}')
        endpoint = OrderCreate(self.account_id, order.data)
        try:
            response = self.api.request(endpoint)
        except (V20Error, OSError) as e:
            logging.error(f'{self.instrument} order failed (aborting): {e}')
        else:
            logging.debug(f'Response: {response}')
            logging.info(f'Order for {self.instrument} placed successfully')
            self.pos = pos_type
Exemplo n.º 29
0
    def place_order(currency_pair, stop_loss, take_profit):

        currency_pair = currency_pair[:3] + '_' + currency_pair[-3:]

        access_token = Config.get('oanda')['api_key']
        account_id = Config.get('oanda')['account_id']

        api = oandapyV20.API(access_token=access_token)

        mkt_order = MarketOrderRequest(
            instrument=currency_pair,
            units=1,
            takeProfitOnFill=TakeProfitDetails(price=take_profit).data,
            stopLossOnFill=StopLossDetails(price=stop_loss).data)

        # create the OrderCreate request
        r = orders.OrderCreate(account_id, data=mkt_order.data)
        try:
            # create the OrderCreate request
            rv = api.request(r)
        except oandapyV20.exceptions.V20Error as err:
            print(r.status_code, err)
        else:
            print(json.dumps(rv, indent=2))
Exemplo n.º 30
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)