Ejemplo n.º 1
0
    def clean(self):
        resp = self.order.get_pending_list()
        time.sleep(1)
        order_dic = from_response_to_dict(resp)

        resp = self.position.get_open_position()
        time.sleep(1)
        pos_dic = from_response_to_dict(resp)

        #保留中の注文をすべてキャンセルする
        if self.has_order(order_dic) is True:
            for i in range(len(order_dic['orders'])):
                order_id = order_dic['orders'][i]['id']
                self.order.cancel_order(order_id)
                time.sleep(1)
            print('cancel order')

        #Oandaのサーバー上に反映されるまで待つ
        while self.has_order(order_dic) is True:
            resp = self.order.get_pending_list()
            time.sleep(1)
            order_dic = from_response_to_dict(resp)
            has_odr = 'exist' if self.has_order(order_dic) is True else 'clean'
            print('pending order: {}'.format(has_odr))

        #保有しているポジションをすべて決済する
        if self.has_position(pos_dic) is True:
            for i in range(len(pos_dic['positions'])):
                instrument = pos_dic['positions'][i]['instrument']
                for order_type in ['long', 'short']:
                    if pos_dic['positions'][i][order_type]['units'] is not '0':
                        data = {'{}Units'.format(order_type): 'ALL'}
                        self.position.close_position(data, instrument)
                        time.sleep(1)
            print('close positon')

        #Oandaのサーバー上に反映されるまで待つ
        while self.has_position(pos_dic) is True:
            resp = self.position.get_open_position()
            time.sleep(1)
            pos_dic = from_response_to_dict(resp)
            has_pos = 'exist' if self.has_position(
                pos_dic) is True else 'clean'
            print('position: {}'.format(has_pos))

        #ORDERモードに状態遷移する
        self.state = 'ORDER'
        print(self.state)
        return self.state
Ejemplo n.º 2
0
    def test_is_reflected_position(self):
        if self.state == 'WAIT_POSITION':
            resp = self.position.get_open_position()
            pos_dic = from_response_to_dict(resp)
            time.sleep(1)

            #empty position for debug
            pos_dic = {'positions': []}

            if not self.has_position(pos_dic) is True:
                return True
        return False
Ejemplo n.º 3
0
    def test_is_reflected_order(self):
        if self.state == 'WAIT_ORDER':
            resp = self.order.get_pending_list()
            order_dic = from_response_to_dict(resp)
            time.sleep(1)

            #empty order for debug
            order_dic = {'orders': []}

            if not self.has_order(order_dic) is True:
                return True
        return False
Ejemplo n.º 4
0
    def close_position(self):
        if self.mode == 'test':
            pass
        else:
            resp = self.position.get_open_position()
            time.sleep(1)
            pos_dic = from_response_to_dict(resp)
            for i in range(len(pos_dic['positions'])):
                instrument = pos_dic['positions'][i]['instrument']
                for order_type in ['long', 'short']:
                    if pos_dic['positions'][i][order_type]['units'] is not '0':
                        data = {'{}Units'.format(order_type): 'ALL'}
                        self.position.close_position(data, instrument)
                        time.sleep(1)

        print('Close position')
        return True
Ejemplo n.º 5
0
    def exec_position(self):
        self.counter += 1
        threshold = 4
        print(f'counter: {self.counter} threshold: {threshold}')
        if self.counter > threshold:
            resp = self.position.get_open_position()
            time.sleep(1)
            pos_dic = from_response_to_dict(resp)
            for i in range(len(pos_dic['positions'])):
                instrument = pos_dic['positions'][i]['instrument']
                for order_type in ['long', 'short']:
                    if pos_dic['positions'][i][order_type]['units'] is not '0':
                        data = {'{}Units'.format(order_type): 'ALL'}
                        self.position.close_position(data, instrument)
                        time.sleep(1)

            print('close position')
            #reset conter
            self.counter = 0

            return True
        else:
            return False
Ejemplo n.º 6
0
def initialize(timeframes: dict,
               instrument: str,
               environment: str = 'demo') -> dict:
    offset_table = {
        '5S': 'S5',
        '10S': 'S10',
        '15S': 'S15',
        '30S': 'S30',
        '1min': 'M1',
        '2min': 'M2',
        '4min': 'M4',
        '5min': 'M5',
        '10min': 'M10',
        '15min': 'M15',
        '30min': 'M30',
        '1T': 'M1',
        '2T': 'M2',
        '4T': 'M4',
        '5T': 'M5',
        '10T': 'M10',
        '15T': 'M15',
        '30T': 'M30',
        '1H': 'H1',
        '2H': 'H2',
        '3H': 'H3',
        '4H': 'H4',
        '6H': 'H6',
        '8H': 'H8',
        '12H': 'H12',
        '1D': 'D',
        '1W': 'W',
        '1M': 'M'
    }

    #解析に用いるローソク足を定義
    candlesticks = {t: CandleStick(t, c) for t, c in timeframes.items()}
    #トレード環境(本番 or 仮想)
    instrument_handler = Instrument(environment)

    #ローソク足データの初期値を設定
    for k, v in candlesticks.items():
        resp = instrument_handler.fetch_candle(instrument, 'M',
                                               offset_table[k], v.count)
        print(resp)

        #接続可能かを検証
        resp.raise_for_status()
        #		try:
        #			resp.raise_for_status()
        #		except ConnectionError as e:
        #			print(f'{e}')
        #			return None

        print('Instrument_handler get connection in Initialize from bot.py')

        #取得したローソク足を辞書型へ変換
        fetched_data = from_response_to_dict(resp)

        time_index = []
        default_ohlc = {'open': [], 'high': [], 'low': [], 'close': []}

        for i in range(v.count):
            #responseから必要なデータを抽出し、順番にリストに格納する
            time_index.append(
                pd.to_datetime(fetched_data['candles'][i]['time']))
            default_ohlc['open'].append(
                float(fetched_data['candles'][i]['mid']['o']))
            default_ohlc['high'].append(
                float(fetched_data['candles'][i]['mid']['h']))
            default_ohlc['low'].append(
                float(fetched_data['candles'][i]['mid']['l']))
            default_ohlc['close'].append(
                float(fetched_data['candles'][i]['mid']['c']))

        #抽出したローソク足データを自作クラスのOHLCに代入
        ohlc = pd.DataFrame(default_ohlc, index=time_index)
        located_ohlc = ohlc.loc[:, ['open', 'high', 'low', 'close']]
        v.ohlc = located_ohlc
        print(f'{k}: {len(v.ohlc.index)}')

    return candlesticks
Ejemplo n.º 7
0
def initialize(timeframes, instrument, environment='demo'):
	print('Initialize start')
	offset_table = {
		'5S': 'S5',
		'10S': 'S10',
		'15S': 'S15',
		'30S': 'S30',
		'1min': 'M1',
		'2min': 'M2',
		'4min': 'M4',
		'5min': 'M5',
		'10min': 'M10',
		'15min': 'M15',
		'30min': 'M30',
		'1T': 'M1',
		'2T': 'M2',
		'4T': 'M4',
		'5T': 'M5',
		'10T': 'M10',
		'15T': 'M15',
		'30T': 'M30',
		'1H': 'H1',
		'2H': 'H2',
		'3H': 'H3',
		'4H': 'H4',
		'6H': 'H6',
		'8H': 'H8',
		'12H': 'H12',
		'1D': 'D',
		'1W': 'W',
		'1M': 'M'
	}

	#timeframesの情報をもとにCandleStickを生成,時間足をキーとして地所型に格納
	candlesticks = {t: CandleStick(t, c) for t, c in timeframes.items()}

	#APIを叩くhandler呼び出し
	instrument_handler = Instrument(environment)
	
	#任意のすべての時間足において、指定された本数のローソク足を取得
	for k, v in candlesticks.items():
		#各時間足ごとのローソク足のデータを取得
		resp = instrument_handler.fetch_candle(instrument, 'M', offset_table[k], v.count)
		print(resp)

		#接続失敗した場合、Noneを返し終了
		try:
			resp.raise_for_status()
		except ConnectionError as e:
			print(f'{e}')
			return None
		print('Pricing handler get connection')

		#取得したローソク足データをdict型へ変換
		fetched_data = from_response_to_dict(resp)

		time_index = []
		default_ohlc = {
			'open': [],
			'high': [],
			'low': [],
			'close': []
		}
		for i in range(v.count):
			#responseから必要なデータを抽出し、順番にリストに格納する
			time_index.append(pd.to_datetime(fetched_data['candles'][i]['time']))
			default_ohlc['open'].append(float(fetched_data['candles'][i]['mid']['o']))
			default_ohlc['high'].append(float(fetched_data['candles'][i]['mid']['h']))
			default_ohlc['low'].append(float(fetched_data['candles'][i]['mid']['l']))
			default_ohlc['close'].append(float(fetched_data['candles'][i]['mid']['c']))
		#抽出したローソク足データを自作クラスのOHLCに代入
		ohlc = pd.DataFrame(default_ohlc, index=time_index)
		located_ohlc = ohlc.loc[:,['open', 'high', 'low', 'close']]
		v.ohlc = located_ohlc
		print(v.ohlc)
		print(len(v.ohlc.index))
	print('initialize end')
	return candlesticks