Esempio n. 1
0
    def __init__(self, wrapper):
        ## Set up with a wrapper inside
        EClient.__init__(self, wrapper)

        self._market_data_q_dict = {}
Esempio n. 2
0
 def __init__(self):
     EWrapper.__init__(self)
     EClient.__init__(self, wrapper=self)
Esempio n. 3
0
 def __init__(self,wrapper):
     EClient.__init__(self,wrapper)  #matches the init of EClient
Esempio n. 4
0
 def __init__(self):
     EWrapper.__init__(self)
     EClient.__init__(self, wrapper=self)
     # self.account = 'DU110641'
     self.positions = []
     self.account_info = []
Esempio n. 5
0
 def __init__(self):
     EClient.__init__(
         self, self)  #Esto inicia conexion con los servidores de TWS IB
Esempio n. 6
0
 def __init__(self):
     EClient.__init__(self, self)
     self.data = []
     self.requestCounter = 0
     self.doneRetrievingHistoricalData = True
Esempio n. 7
0
 def __init__(self):
     wrapper.EWrapper.__init__(self)
     EClient.__init__(self, wrapper=self)
     self.reqIsFinished = True
     self.started = False
     self.nextValidOrderId = 0
Esempio n. 8
0
 def __init__(self, sqlLink, priceTableNameIndex, sizeTableNameIndex):
     EClient.__init__(self, self)
     self.file = ""
     self.sqlLink = sqlLink
     self.priceTableNameIndex = priceTableNameIndex
     self.sizeTableNameIndex = sizeTableNameIndex
Esempio n. 9
0
    def __init__(self):
        EClient.__init__(self, self)

        self.me_dict = {}
        self.contract_details = {
        }  #Contract details will be stored here using reqId as a dictionary key
Esempio n. 10
0
 def __init__(self):
     EClient.__init__(self, self)
     self.reqId = None
     self.price = None
Esempio n. 11
0
 def __init__(self, port, client_id):
     wrapper.EWrapper.__init__(self)
     EClient.__init__(self, wrapper=self)
     self.client_id = client_id
     self.port = port
Esempio n. 12
0
    def __init__(self, client_id, args, start_order_id=None):
        EClient.__init__(self, self)
        self.client_id = client_id
        self.args = args
        self.start_order_id = start_order_id
        self.logger = logging.getLogger(__name__)

        self.debug_mode = False
        if args.debug:
            self.debug_mode = True

        self.logger.info(
            f'Starting with args -'
            f' symbol: {self.args.symbol},'
            f' order_type: {self.args.order_type},'
            f' quote_type: {self.args.quote_type},'
            f' order_size: {self.args.order_size},'
            f' bar_period: {self.args.bar_period}')

        self.logfile_candles = 'logs/log_candles.csv'
        logfile_candles_rows = ('time', 'symbol', 'open', 'high', 'low', 'close', 'ha_open', 'ha_close', 'ha_high', 'ha_low', 'ha_color')
        self.logfile_orders = 'logs/log_orders.csv'
        logfile_orders_rows = ('time', 'order_id', 'symbol', 'side', 'order_type', 'size', 'price')
        if not os.path.isdir('logs/'):
            os.makedirs('logs')
        if not os.path.exists(self.logfile_candles):
            self._write_csv_row((logfile_candles_rows,), self.logfile_candles, newfile=True)
        else:
            self._write_csv_row((('', '', '', '', '', '', '', '', '', '', ''),), self.logfile_candles)
        if not os.path.exists(self.logfile_orders):
            self._write_csv_row((logfile_orders_rows,), self.logfile_orders, newfile=True)
        else:
            self._write_csv_row((('', '', '', '', '', '', ''),), self.logfile_orders,)

        self.candle_calc_use_prev_ha = True
        self.RT_BAR_PERIOD = MarketDataApp.RT_BAR_PERIOD
        self.RT_BAR_DATA_TYPE = 'MIDPOINT' # MIDPOINT/TRADES/BID/ASK
        self.HISTORICAL_BAR_DATA_TYPE = 'MIDPOINT' # MIDPOINT/TRADES/BID/ASK
        self.period = args.bar_period
        self.order_type = args.order_type
        self.order_size = args.order_size
        df_cols = {
            'time': [],
            'open': [],
            'high': [],
            'low': [],
            'close': [],
            'ha_open': [],
            'ha_close': [],
            'ha_high': [],
            'ha_low': [],
            'ha_color': [],
        }
        self.candles = pd.DataFrame(df_cols)
        self.cache = []
        self._tohlc = tuple() # Real-time 5s update data from IB
        self.first_order = True # Set to False after first order

        #
        self.best_bid = None
        self.best_ask = None
        self.last = None # Last trade price, as received from RealTimeBars

        self.cancel_enable = False

        self.contract = self._create_contract_obj()
        self.contract_details = None

        #
        if not hasattr(self, 'mktData_reqId'):
            # First time init of object
            self.mktData_reqId = random.randint(0, 999)
        if not hasattr(self, 'rtBars_reqId'):
            # First time init of object
            while True:
                self.rtBars_reqId = random.randint(0, 999)
                if not self.rtBars_reqId == self.mktData_reqId:
                    break
        if not hasattr(self, 'historicalData_reqId'):
            # First time init of object
            while True:
                self.historicalData_reqId = random.randint(0, 999)
                if not self.historicalData_reqId in (self.mktData_reqId, self.mktData_reqId):
                    break

        if not self.debug_mode:
            # Connect to server and start feeds
            self._connect()
            self._cancel_orders()
            self._subscribe_mktData()
            self._subscribe_rtBars()
        else:
            # Run test setup here
            self._connect()
            self._test_setup()

        if not hasattr(self, 'order_id'):
            # Allow for obj to re __init__() and not reset self.order_id
            if self.start_order_id is not None:
                self.order_id = self.start_order_id
            else:
                self._update_order_id()
                #self.order_id = 0 # Placeholder. Will get updated prior to any order, via _place_order()
        else:
            pass
Esempio n. 13
0
 def __init__(self):
     EClient.__init__(self, self)
     self.bars = pd.DataFrame()
Esempio n. 14
0
    def __init__(
        self,
        contract: IBContract,
        invest: float,
        s_window: int,
        l_window: int,
        update_interval: int = 15,
        band_offset: float = 0.1,
    ) -> None:
        assert (isinstance(contract, IBContract))
        assert (0 < invest if isinstance(invest, float) else False)
        assert (0 < s_window if isinstance(s_window, int) else False)
        assert (0 < l_window if isinstance(l_window, int) else False)
        assert (s_window < l_window)
        assert (15 <= update_interval
                if isinstance(update_interval, int) else False)
        assert (0 < band_offset if isinstance(band_offset, float) else False)

        EClient.__init__(self, self)
        self.connect('127.0.0.1', 7497, 0)

        self.contract = contract
        self.invest = invest
        self.s_window, self.l_window = s_window, l_window
        self.s_alpha, self.l_alpha = 2 / (s_window + 1), 2 / (l_window + 1)
        self.update_interval = update_interval
        self.band_offset = band_offset

        self.odir = Path('sg3tws_out')
        self.rid = itertools.count()
        self.oid = itertools.count(start=1)

        # init market data subscription
        self.data = {
            'DELAYED_ASK': 0,
            'DELAYED_BID': 0,
            'DELAYED_ASK_SIZE': 0,
            'DELAYED_BID_SIZE': 0,
            'DELAYED_VOLUME': 0,
            'DELAYED_LAST': 0,
            'DELAYED_LAST_SIZE': 0,
            'DELAYED_HIGH': 0,
            'DELAYED_LOW': 0,
            'DELAYED_CLOSE': 0,
            'DELAYED_OPEN': 0
        }

        self.df_data = pd.DataFrame(columns=list(self.data.keys()))
        self.df_data.index.name = 'time'
        self.data_file = self.odir.join('data.csv')
        self.df_data.to_csv(self.data_file)

        self.reqMarketDataType(3)
        self.reqMktData(next(self.rid), self.contract, '', False, False, [])

        # init account data subscription
        self.account = {'TotalCashValue': 0., 'GrossPositionValue': 0.}
        self.df_account = pd.DataFrame(columns=list(self.account.keys()))
        self.df_account.index.name = 'time'
        self.account_file = self.odir.join('account.csv')
        self.df_account.to_csv(self.account_file)
        self.reqAccountSummary(next(self.rid), 'All',
                               ', '.join(self.account.keys()))

        # init trades log
        self.n_order = itertools.count(1)
        self.orders = {
            'time': datetime.datetime.now(),
            'oid': 0,
            'shares': 0,
            'avg_price': 0.,
            'tick_price': 0.,
            'commission': 0.,
            'total': 0.,
            'exchange': ''
        }
        self.df_orders = pd.DataFrame(columns=list(self.orders.keys()))
        self.df_orders.index.name = 'n'
        self.orders_file = self.odir.join('orders.csv')
        self.df_orders.to_csv(self.orders_file)

        # init technical analysis
        self.fields = [
            'price', 'mal', 'mas', 'mao', 'ub', 'lb', 'cash', 'stock', 'pos',
            'total hold', 'total'
        ]
        self.stat = dict(
            zip(self.fields, np.zeros_like(self.fields, dtype=np.float)))

        self.df_stat = pd.DataFrame(columns=self.fields)
        self.df_stat.index.name = 'time'
        self.stat_file = self.odir.join('stat.csv')
        self.df_stat.to_csv(self.stat_file)

        # init plotting
        register_matplotlib_converters()
        self.fig, self.axes = plt.subplots(nrows=4, sharex='all')
        self.fig.set(figwidth=10, figheight=9)
        self.axes[0].set_title('SG3TWS {}'.format(self.contract.symbol),
                               fontsize=18)
        self.axes[0].set_ylabel('Price', fontsize=14)
        self.axes[1].set_ylabel('Oscillator', fontsize=14)
        self.axes[1].axhline(y=0, ls='-', c='k')
        self.axes[2].set_ylabel('Position', fontsize=14)
        self.axes[3].set_ylabel('Portfolio value', fontsize=14)
        self.axes[3].set_xlabel('Time', fontsize=14)
        self.lines = {
            'price': self.axes[0].plot([], [], label='price')[0],
            'mas': self.axes[0].plot([], [], label='mas')[0],
            'mal': self.axes[0].plot([], [], label='mal')[0],
            'mao': self.axes[1].plot([], [], label='mao')[0],
            'ub': self.axes[1].plot([], [], '--k', label='ub')[0],
            'lb': self.axes[1].plot([], [], '--k', label='lb')[0],
            'pos': self.axes[2].plot([], [], label='position')[0],
            'total hold': self.axes[3].plot([], [], label='total hold')[0],
            'total': self.axes[3].plot([], [], label='total')[0],
        }
        for ax in self.axes:
            ax.legend()
        self.fig.tight_layout()

        # initiate TWS-API loop and strategy loop
        threading.Thread(target=self.run, args=()).start()
        threading.Thread(target=self.exec, args=()).start()
Esempio n. 15
0
 def __init__(self):
     EClient.__init__(self, self)
     self.lastStamp = datetime.datetime.utcnow()
Esempio n. 16
0
 def __init__(self, pairs):
     EClient.__init__(self, self)
     self.pairs = pairs
     self.data = {}
     for cp in pairs:
         self.data[cp.pair()] = []
Esempio n. 17
0
 def __init__(self):
     EClient.__init__(self, self)
     self.bardata = {}  #Initialize dictionary to store bar data
     self.orderinfo = []
     self.connection = None
     self.submit_flag = False
Esempio n. 18
0
    def __init__(self, wrapper):
        ## Set up with a wrapper inside
        EClient.__init__(self, wrapper)

        self._market_data_q_dict = {}
        self._commissions = list_of_execInformation()
Esempio n. 19
0
 def __init__(self):
     EClient.__init__(self, self)
     self.file = ""
Esempio n. 20
0
 def __init__(self):
     EClient.__init__(self, self)
     self.last_price: typing.Optional[float] = None
     self.next_order_id: typing.Optional[int] = None
     self.next_order: typing.Optional[BracketOrder] = None
Esempio n. 21
0
 def __init__(self):
     EClient.__init__(self, self)
     self.data = []  #Initialize variable to store candle
Esempio n. 22
0
 def __init__(self, wrapper, reqIDoffset, log=logtoscreen()):
     ## Set up with a wrapper inside
     EClient.__init__(self, wrapper)
     self.ib_init_request_id_factory(reqIDoffset)
     self.log = log
Esempio n. 23
0
 def __init__(self):
     EClient.__init__(self, self)
     self.started = False
     self.globalCancelOnly = False
Esempio n. 24
0
 def __init__(self):
     EClient.__init__(self, self)
     self.qs = defaultdict(list)
     self._my_contract_details = {}
     self._my_historic_data_dict = {}
Esempio n. 25
0
 def __init__(self):
     EClient.__init__(self, self)
Esempio n. 26
0
 def __init__(self, wrapper):
     ## Set up with a wrapper inside
     EClient.__init__(self, wrapper)
Esempio n. 27
0
 def __init__(self, wrapper):
     EClient.__init__(self, wrapper)
 def __init__(self, wrapper):
     ## Set up with a wrapper inside
     EClient.__init__(self, wrapper)
     ## Dict to hold queue object for requesting amrket data
     self._market_data_q_dict = {}
Esempio n. 29
0
    def __init__(self):
        EClient.__init__(self, self)

        self.positions = {}
        self.currentDataReqId = 0
        self.dataReqIds = {}
 def __init__(self):
     EClient.__init__(self, self)
     self.data = {}
Esempio n. 31
0
 def __init__(self, callback:Callable[[str, Dict], Any]  ):
     wrapper.EWrapper.__init__(self)
     EClient.__init__(self, wrapper=self)
     
     self.sendMessage = callback
     self.EVENT_IS_CONNECTED = threading.Event()                  # Events for main thread    
 def __init__(self, wrapper):
     ## Set up with a wrapper inside
     EClient.__init__(self, wrapper)