def close_position(self, instrument, longUnits='ALL', shortUnits='ALL'): instrument = get_symbol(instrument) response = self.api.position.close(self.account_id, instrument, longUnits=longUnits, shortUnits=shortUnits) if response.status < 200 or response.status > 299: log_error(logger, response, 'CLOSE_POSITION') raise Exception(response.body['errorMessage']) longOrderCreateTransaction = response.get('longOrderCreateTransaction', None) longOrderFillTransaction = response.get('longOrderFillTransaction', None) longOrderCancelTransaction = response.get('longOrderCancelTransaction', None) shortOrderCreateTransaction = response.get( 'shortOrderCreateTransaction', None) shortOrderFillTransaction = response.get('shortOrderFillTransaction', None) shortOrderCancelTransaction = response.get( 'shortOrderCancelTransaction', None) relatedTransactionIDs = response.get('relatedTransactionIDs', None) lastTransactionID = response.get('lastTransactionID', None) print(longOrderCreateTransaction.__dict__) print(longOrderFillTransaction.__dict__) print(longOrderCancelTransaction.__dict__) print(shortOrderCreateTransaction.__dict__) print(shortOrderFillTransaction.__dict__) print(shortOrderCancelTransaction.__dict__) print(relatedTransactionIDs.__dict__) print(lastTransactionID) return True
def get_price(self, instrument, type='mid'): instrument = get_symbol(instrument) if not self._prices: self.list_prices() if instrument not in self._prices: self.list_prices(instruments=[instrument]) price = self._prices.get(instrument) if type == 'mid': return (price['bid'] + price['ask']) / 2 elif type == 'bid': return price['bid'] elif type == 'ask': return price['ask']
def pull_position(self, instrument): """pull position by instrument""" instrument = get_symbol(instrument) response = self.api.position.get(self.account_id, instrument) if response.status < 200 or response.status > 299: log_error(logger, response, 'QEURY_POSITION') raise Exception(response.body['errorMessage']) last_transaction_id = response.get('lastTransactionID', 200) position = response.get('position', 200) if position: self.positions[position.instrument] = position return position
def get_candle(self, instrument, granularity, count=None, fromTime=None, toTime=None, price_type='M', smooth=False): instrument = get_symbol(instrument) granularity = get_timeframe_granularity(granularity) if isinstance(fromTime, str): fromTime = dateparser.parse(fromTime).strftime('%Y-%m-%dT%H:%M:%S') elif fromTime: fromTime = fromTime.strftime('%Y-%m-%dT%H:%M:%S') if isinstance(toTime, str): toTime = dateparser.parse(toTime).strftime('%Y-%m-%dT%H:%M:%S') elif toTime: toTime = toTime.strftime('%Y-%m-%dT%H:%M:%S') if toTime: response = self.api.instrument.candles(instrument, granularity=granularity, fromTime=fromTime, toTime=toTime, price=price_type, smooth=smooth) else: response = self.api.instrument.candles(instrument, granularity=granularity, count=count, fromTime=fromTime, price=price_type, smooth=smooth) if response.status != 200: logger.error('[GET_Candle]', response, response.body) return [] candles = response.get("candles", 200) price = 'mid' if price_type == 'B': price = 'bid' elif price_type == 'A': price = 'ask' data = [[candle.time.split(".")[0], getattr(candle, price, None).o, getattr(candle, price, None).h, getattr(candle, price, None).l, getattr(candle, price, None).c, candle.volume] for candle in candles] df = pd.DataFrame(data, columns=['time', 'open', 'high', 'low', 'close', 'volume']) df['time'] = pd.to_datetime(df['time']) df = df.set_index('time') df.head() return df
def trade_units(self, instrument, stop_loss_pips): """get max units for this instrument""" instrument = get_symbol(instrument) pip_unit = pip(instrument) risk = self.equity * self.risk_ratio value = risk / stop_loss_pips / pip_unit if instrument.upper().startswith('USD'): price = self.account.get_price(instrument) value = value * price elif instrument.upper().endswith('USD'): pass else: # cross pair raise NotImplementedError return int(value / 100) * 100
def run(self): print('%s statup.' % self.__class__.__name__) print('Registered handler: %s' % ', '.join([x.__class__.__name__ for x in self.handlers])) pairs_oanda = [get_symbol(p) for p in self.pairs] pair_list = ",".join(pairs_oanda) print('Pairs:', pair_list) print('\n') stream_api = self.account.stream_api response = stream_api.pricing.stream( self.account_id, instruments=pair_list, snapshot=True, ) for msg_type, msg in response.parts(): if msg_type == "pricing.PricingHeartbeat": self.put(HeartBeatEvent()) elif msg_type == "pricing.ClientPrice" and msg.type == 'PRICE': instrument = msg.instrument time = dateparser.parse(msg.time) bid = Decimal(str(msg.bids[0].price)) ask = Decimal(str(msg.asks[0].price)) self.put( TickPriceEvent(self.broker, instrument, time, bid, ask)) else: print('Unknow type:', msg_type, msg.__dict__) while True: event = self.get(False) if event: self.handle_event(event) else: break if not self.running: self.stop()
def open(self, event): instrument = get_symbol(event.instrument) if event.order_type == 'market': if event.side == 'buy': mktOrder = MarketOrderRequest( instrument=instrument, units=event.units, # type= event.order_type, # side= event.side ) if event.side == 'sell': mktOrder = MarketOrderRequest( instrument=instrument, units=(event.units * -1), # type= event.order_type, # side= event.side ) else: print('Order Type Not Supported ' + self.order_type) return accountID = self.account_id access_token = self.access_token api = oandapyV20.API(access_token=access_token) r = orders.OrderCreate(accountID, data=mktOrder.data) try: # Try and execute order rv = api.request(r) # response = self.conn.getresponse().read().decode("utf-8").replace("\n","").replace("\t","") logger.debug(json.dumps(rv, indent=2)) except oandapyV20.exceptions.V20Error as err: print(r.status_code, err) else: print(json.dumps(rv, indent=2))
def _process_order_paramters(self, **kwargs): data = {} instrument = None pip_unit = None if kwargs.get('instrument'): instrument = get_symbol(kwargs['instrument']) data['instrument'] = instrument if kwargs.get('trade_id'): data['tradeID'] = str(kwargs['trade_id']) trade = self.trades.get(data['tradeID']) or self.get_trade( data['tradeID']) instrument = trade.instrument if instrument: pip_unit = pip(instrument) if kwargs.get('lots'): units = lots_to_units(kwargs['lots'], kwargs.get('side') or OrderSide.BUY) data['units'] = str(units) if kwargs.get('type'): data['type'] = kwargs['type'] if kwargs.get('timeInForce'): data['timeInForce'] = kwargs['timeInForce'] or TimeInForce.FOK if kwargs.get('priceBound'): data['priceBound'] = str(kwargs['priceBound']) if kwargs.get('price'): data['price'] = str(kwargs['price']) if kwargs.get('positionFill'): data['positionFill'] = kwargs[ 'positionFill'] or OrderPositionFill.DEFAULT # The Client Extensions to update for the Order. Do not set, modify, or # delete clientExtensions if your account is associated with MT4. if kwargs.get('client_id') or kwargs.get('client_tag') or kwargs.get( 'client_comment'): data['clientExtensions'] = ClientExtensions( id=kwargs['client_id'], tag=kwargs['client_tag'], comment=kwargs['client_comment']) if kwargs.get('trade_client_id') or kwargs.get( 'trade_client_tag') or kwargs.get('trade_client_comment'): data['tradeClientExtensions'] = ClientExtensions( id=kwargs['trade_client_id'], tag=kwargs['trade_client_tag'], comment=kwargs['trade_client_comment']) if kwargs.get('take_profit_price'): data['takeProfitOnFill'] = TakeProfitDetails( price=str(kwargs['take_profit_price']), clientExtensions=data.get('clientExtensions')) if kwargs.get('stop_loss_pip') and pip_unit: stop_loss_price = pip_unit * Decimal(str(kwargs['stop_loss_pip'])) data['stopLossOnFill'] = StopLossDetails( distance=str(stop_loss_price), clientExtensions=data.get('clientExtensions')) if kwargs.get('stop_loss_distance'): data['stopLossOnFill'] = StopLossDetails( distance=str(kwargs['stop_loss_distance']), clientExtensions=data.get('clientExtensions')) if kwargs.get('trailing_pip'): trailing_distance_price = pip_unit * Decimal( str(kwargs['trailing_pip'])) data['trailingStopLossOnFill'] = TrailingStopLossDetails( distance=str(trailing_distance_price), clientExtensions=data.get('clientExtensions')) if kwargs.get('trigger_condition'): data['triggerCondition'] = kwargs[ 'trigger_condition'] or OrderTriggerCondition.DEFAULT if kwargs.get('gtd_time'): # todo confirm gtdTime format data['gtdTime'] = str(kwargs['gtd_time']) if kwargs.get('client_trade_id'): data['clientTradeID'] = kwargs['client_trade_id'] if kwargs.get('guaranteed'): data['guaranteed'] = kwargs['guaranteed'] if kwargs.get('distance'): data['distance'] = kwargs['distance'] return data