示例#1
0
    def __init__(self, loss_tolerance, liquid_assets=0, invested_assets=0):
        self.assets = Assets(liquid_assets, invested_assets)
        self.price = Prices()
        self.price_watcher = PriceWatcher(self)

        self.initial_investment = None
        self.loss_tolerance = loss_tolerance
        self.loss_tolerance_price = None
        self.gain_threshold_met = False
        self.assets_are_liquid = True
        self.is_trading = True
        self.first_trade = True
示例#2
0
 def __init__(self,
              wallet,
              ticker=None,
              strategy=None,
              start_date=None,
              mode=MODE_SIMULATED):
     self._on_off = True
     self._ticker = ticker
     self._strategy = strategy
     self._wallet = wallet
     self._prices = Prices(self._ticker)
     if start_date != None:
         self._prices.setDatePoint(start_date)
     self._mode = mode
示例#3
0
 def __init__(self):
     self.d = Downloader(wait=0.0)
     self.m = Manufacturing()
     self.p = Prices()
     self.g = Groups()
     
     self.results = {}
示例#4
0
    def __init__(self, window=None):
        wrapper.EWrapper.__init__(self)
        client.EClient.__init__(self, wrapper=self)
        #QtWidgets.QThread.__init__(self, None)

        self.reqMarketDataType(
            wrapper.MarketDataTypeEnum.DELAYED)  #Use delayed data
        self.nextValidOrderId = 1
        self.permId2ord = {}
        self.req_to_table_row = {}
        self.tracked_names = {}
        self.account_details = {}
        self.positions = {}
        self.open_orders = {}
        if window: self.window = window
        self.prices_history = Prices()
        self.portfolio_value_hist = {}
        self.req_to_strategy = {}
        self.strategies = {}
示例#5
0
def send_updates():

    p = Prices(prices_db)
    p.create_tab()
    current_date = datetime.today().strftime("%d-%m-%Y")
    day_before_current_date = datetime.today() - timedelta(1)
    day_before_current_date = day_before_current_date.strftime("%d-%m-%Y")
    message = p.check_price_change(day_before_current_date, current_date)

    if len(message) > 0:

        u = Users(users_db)
        u.create_tab()
        where_to_send = u.get_users_chatid_to_update()

        if len(where_to_send) > 0:
            where_to_send = [x[0] for x in where_to_send]

            for user_chat_id in where_to_send:
                send_message(user_chat_id, cheeze_token, message)
示例#6
0
def setup():
    conf = Configuration('..')
    prices_manager = Prices('prices', conf['se'])
    today = date.today()
    range_dates = ('2017-01-01', today.isoformat())

    ckp_manager = CheckpointManager('checkpoint')
    data = ckp_manager.load_base()

    if data is not None:
        print('last checkpoint loaded')
        symbols = data['symbols']
        all_data = data['all_data']
    else:
        blacklist = set(['CAPU', 'PESA', 'PSUR', 'POLL'])
        symbols = conf.symbols()
        all_data = load_all_data(prices_manager, blacklist, symbols,
                                 range_dates)

        print('calculating returns')
        for data in all_data.values():
            # TODO there must be a better way to do this
            returns = pd.DataFrame(data['Adj Close']).apply(
                lambda x: np.log(x) - np.log(x.shift()))
            data['Daily Return'] = returns

        state = {
            'all_data': all_data,
            'symbols': symbols,
        }

        ckp_manager.save_base(state)

    print("using dates [%s - %s]" % range_dates)

    # strategy = StrategyFindBestMA(ckp_manager)
    strategy = StrategyRandom01(ckp_manager)
    print(f'using strategy {type(strategy).__name__}')
    strategy.load(all_data.keys(), all_data)

    return (today, range_dates, conf, prices_manager, all_data, ckp_manager,
            strategy)
示例#7
0
def getCheesePrice(save_to_db=False, check_price=False):
    """ Залезает на сайт parmezan.ru и вытаскивает оттуда цены"""

    cheesePriceId = {
        "Фестивальный": "fest_24-price",
        "Истринский": "ber_1-price",
        "Винный": "vai_3-price",
        "Медовый": "med_23-price",
        "Пивной": "bir_5-price",
        "Тирольский": "tirol_22-price",
        "Пошехонский": "posh_76-price",
        "Колмогоровский": "kolmo_15-price",
        "Золотой рубль": "gold_16-price",
        "Губернаторский": "gub_6-price",
        "Красногорский": "krest_17-price",
        "Свежий для жарки": "sve_7-price"
    }

    url = "https://parmezan.ru/Zakaz"
    res = requests.get(url)
    page = res.text
    soup = BeautifulSoup(page, 'html.parser')
    cheesePrice = {}

    for k, v in cheesePriceId.items():
        if soup.find(id=v) is not None:
            cheesePrice[k] = soup.find(id=v).text.strip()

    if save_to_db:

        p = Prices(prices_db)
        p.create_tab()
        current_date = datetime.today().strftime("%d-%m-%Y")
        all_dates = list(set([x[0] for x in p.show_dates()]))

        if current_date not in all_dates:
            for k, v in cheesePrice.items():
                p.addprice(cheesePriceId[k], k, v, current_date)
            print("add to db")
        else:
            print(f"На {current_date} уже загружены цены")

    return cheesePrice
示例#8
0
    # for i in xrange(3,50):
    #   for j in xrange(1, i-1):
    #     ip.setParams(j,i)
    #     currentProfit = calculateProfit(ip)
    #     if currentProfit > bestProfit:
    #       bestProfit = currentProfit
    #       bestParams = (j,i)
    #       print "best profit is : ", currentProfit, " with params: ", bestParams

    # ip.setParams(bestParams[0], bestParams[1])
    # calculateProfit(ip, True)

    try:
        myTrader = trader.Trader()
        coinStr = 'ltc'
        prices = Prices(coinStr + '_usd')
        interval = 1800
        COIN_MIN = 1
        DOLLAR_MIN = 10
        emaPair = (8, 17)
        diffPerc = 1.003

        def tradeIfShould(ip):
            timestamp = (int(time.time()) / 60) * 60
            if timestamp in ip.timeline:
                current = ip.timeline[timestamp]
            else:
                current = ip.timeline[ip.getMostRecentTime()]
            firstKey = ip.getFirstAvgKey()
            secondKey = ip.getSecondAvgKey()
            info = myTrader.getInfo()
示例#9
0
                row_date = from_req_str(datum[0])
                dates.append(row_date)

                cols = [float(x.replace(',', '')) for x in datum[1:]]
                prices_data.append(cols)

        prices = pd.DataFrame(data=prices_data,
                              index=dates,
                              columns=[
                                  'Open', 'Max', 'Min', 'Close', 'Adj Close',
                                  'Volumen monto', 'Volumen nominal'
                              ])
        prices.index.name = 'Date'

        if cur_prices is None:
            cur_prices = prices
        else:
            cur_prices = cur_prices.append(prices, sort=True)
            cur_prices.drop_duplicates(keep='last', inplace=True)

        prices_manager.save(symbol, cur_prices)


if __name__ == '__main__':
    conf = Configuration('..')
    downloader = Downloader('cache')
    prices_manager = Prices('prices', conf['se'])
    _setup_symbols()
    _update_prices()
示例#10
0
class Trader:
    def __init__(self, loss_tolerance, liquid_assets=0, invested_assets=0):
        self.assets = Assets(liquid_assets, invested_assets)
        self.price = Prices()
        self.price_watcher = PriceWatcher(self)

        self.initial_investment = None
        self.loss_tolerance = loss_tolerance
        self.loss_tolerance_price = None
        self.gain_threshold_met = False
        self.assets_are_liquid = True
        self.is_trading = True
        self.first_trade = True

    def start(self):
        self.price_watcher.start()

    def assess_prices(self, current_price):
        if not self.is_trading:
            print("NOT TRADING: " + str(current_price))
        else:
            print("TRADING: " + str(current_price))

            self.price.update_prices(current_price)

            if self.first_trade:
                self.assets.invest_assets()
                self.first_trade = False

            self.assets.calculate_asset_value(self.price.percent_change)

            if self.loss_tolerance_price is None:
                self.calculate_loss_tolerance_price()

            if self.price.percent_change > 5:
                self.gain_threshold_met = True

            if self.gain_threshold_met:
                self.threshold_met_strategy()
            else:
                self.threshold_not_met_strategy()

    def calculate_loss_tolerance_price(self):
        decimal = self.loss_tolerance / 100
        loss_amount = decimal * self.price.initial_price
        self.loss_tolerance_price = self.price.initial_price - loss_amount

    def threshold_met_strategy(self):
        sell_price = self.price.high_price - self.price.initial_price / 2
        if sell_price > self.price.current_price:
            self.assets.sell_assets()

    def threshold_not_met_strategy(self):
        if self.loss_tolerance_price > self.price.current_price:
            #sell, record
            self.assets.sell_assets()

    def reset(self):
        self.initial_investment = None
        self.loss_tolerance_price = None
        self.gain_threshold_met = False
        self.assets_are_liquid = True
示例#11
0
eps       = 0.0035
use_email = False
phase     = 'buy'

pair = "ETH/USD" if len(sys.argv) == 1 else sys.argv[1].upper() + "/USD"

conn = ccxt.kraken({
        "apiKey" : secrets.publickey,
        "secret" : secrets.privatekey
})

start_usd = conn.fetchBalance()['free'][pair[-3:]]
start_coin = conn.fetchBalance()['free'][pair[:3]]

w = Wallet(start_usd, start_coin, phase)
prices = Prices(conn, pair, short_len, long_len)
if use_email: em = Emailer(secrets.myaddress, secrets.mypassword)

while True:
    if len(prices.prices) < prices.long_len:
        print("%i: Warming up..." % len(prices.prices))
        prices.addCurrentPrice()
        time.sleep(SLEEP_SEC)
        continue

    prices.addCurrentPrice()
    prices.updateMA()

    if len(prices.prices) % 20 == 0:
        checkin(w, prices)
示例#12
0
def main():
    prices = Prices()
    weather = Weather()

    def wake_up_routine(number):
        if number == 1:
            w1 = Weather()
            send_message = "God morgen Tommy! I dag kan du forvente følgende temperaturer " + w1.min_max_weather(
            )
            channel = "raspberry-pi"
            slack_client.api_call("chat.postMessage",
                                  channel=channel,
                                  text=send_message)
            audio = AudioPlayer()
            audio.music_then_radio("random", 10, 300, "random")

    def send_bitcoin_price(channel):
        price_bit = prices.get_bitcoin_price()
        send_msg_bit = "Den nåværende prisen for Bitcoin er: " + price_bit[0]
        returns_msg_bit = "Din nåværende avkastning på Bitcoin er: " + price_bit[
            1]
        slack_client.api_call("chat.postMessage",
                              channel=channel,
                              text=send_msg_bit)
        slack_client.api_call("chat.postMessage",
                              channel=channel,
                              text=returns_msg_bit)

    def send_dogecoin_price(channel):
        price_dog = prices.get_dogecoin_price()
        send_msg_dog = "Den nåværende prisen for Dogecoin er: " + price_dog[0]
        # returns_msg_dog = "Din nåværende avkastning på Bitcoin er: " + price_dog[1]
        slack_client.api_call("chat.postMessage",
                              channel=channel,
                              text=send_msg_dog)
        # slack_client.api_call("chat.postMessage", channel=channel, text=returns_msg_dog)

    def send_litecoin_price(channel):
        price_ltc = prices.get_litecoin_price()
        send_msg_ltc = "Den nåværende prisen for Litecoin er: " + price_ltc[0]
        returns_msg_ltc = "Din nåværende avkastning på Litecoin er: " + price_ltc[
            1]
        slack_client.api_call("chat.postMessage",
                              channel=channel,
                              text=send_msg_ltc)
        slack_client.api_call("chat.postMessage",
                              channel=channel,
                              text=returns_msg_ltc)

    def morning_messages():
        time = datetime.now().time()
        hour = str(time)[0:2]
        global sent
        if hour == "09" and not sent:
            morning_prices()
            morning_weather()
            sent = True
        if hour == "10" and sent:
            sent = False

    def morning_weather():
        curr_weather = weather.min_max_weather().split()
        minimum = curr_weather[0]
        maximum = curr_weather[1]
        send_message = f"I dag kan du forvente temperaturer mellom {minimum} og {maximum}."
        channel = "raspberry-pi"
        slack_client.api_call("chat.postMessage",
                              channel=channel,
                              text=send_message)

    def morning_prices():
        channel = "raspberry-pi"
        good_morning_msg = "God morgen Tommy! Håper du får en fin dag :)"
        slack_client.api_call("chat.postMessage",
                              channel=channel,
                              text=good_morning_msg)
        send_bitcoin_price(channel)
        send_dogecoin_price(channel)
        send_litecoin_price(channel)

    tokens = {}
    with open('configs.json') as json_data:
        tokens = json.load(json_data)
    slack_client = SlackClient(tokens.get("slack_bot_token"))
    alarm = Alarm()
    if slack_client.rtm_connect(auto_reconnect=True):
        print("Connected!")
        while True:
            morning_messages()
            try:
                messages = slack_client.rtm_read()
            except:
                print("Disconnected.")
                print("Reconnecting...")
                time.sleep(20)
                slack_client.rtm_connect()
                messages = slack_client.rtm_read()
            if alarm.alarm_active():
                if alarm.check_alarm():
                    wake_up_routine(1)
            # print(messages)
            if messages:
                for message in messages:
                    if message.get("subtype") is None and message.get(
                            'user') is not None and message.get(
                                'text'
                            ) is not None and "BOT TEST" in message.get(
                                'text'):
                        channel = message["channel"]
                        send_message = "Responding to `BOT TEST` message sent by user <@%s>" % message[
                            "user"]
                        slack_client.api_call("chat.postMessage",
                                              channel=channel,
                                              text=send_message)

                    if message.get("subtype") is None and message.get(
                            'user') is not None and message.get(
                                'text') is not None and "audio" in message.get(
                                    'text'):
                        command = message.get('text')
                        command_lst = command.split()
                        command = " ".join(command_lst[1:])
                        au1 = AudioPlayer()
                        au1.audio_handler(command)

                    if message.get("subtype") is None and message.get(
                            'user') is not None and message.get(
                                'text'
                            ) is not None and "weather_now" in message.get(
                                'text'):
                        command = message.get('text')
                        command_lst = command.split()
                        command = " ".join(command_lst[1:])
                        weather = Weather()
                        send_message = weather.weather_handler(command)
                        channel = message["channel"]
                        slack_client.api_call("chat.postMessage",
                                              channel=channel,
                                              text=send_message)

                    if message.get("subtype") is None and message.get(
                            'user') is not None and message.get(
                                'text'
                            ) is not None and "weather_min_max" in message.get(
                                'text'):
                        weather = Weather()
                        send_message = weather.min_max_weather()
                        channel = message["channel"]
                        slack_client.api_call("chat.postMessage",
                                              channel=channel,
                                              text=send_message)

                    if message.get("subtype") is None and message.get(
                            'user') is not None and message.get(
                                'text'
                            ) is not None and "set_alarm" in message.get(
                                'text'):
                        command = message.get('text')
                        command_lst = command.split()
                        alarm.set_alarm(int(command_lst[1]),
                                        int(command_lst[2]),
                                        int(command_lst[3]),
                                        int(command_lst[4]))

                    if message.get("subtype") is None and message.get(
                            'user'
                    ) is not None and message.get(
                            'text'
                    ) is not None and "get_bitcoin_price" in message.get(
                            'text'):
                        send_bitcoin_price(message["channel"])

                    if message.get("subtype") is None and message.get(
                            'user'
                    ) is not None and message.get(
                            'text'
                    ) is not None and "get_dogecoin_price" in message.get(
                            'text'):
                        send_dogecoin_price(message["channel"])

                    if message.get("subtype") is None and message.get(
                            'user'
                    ) is not None and message.get(
                            'text'
                    ) is not None and "get_litecoin_price" in message.get(
                            'text'):
                        send_litecoin_price(message["channel"])

                    if message.get("subtype") is None and message.get(
                            'user'
                    ) is not None and message.get(
                            'text'
                    ) is not None and "get_crypto_price" in message.get(
                            'text'):
                        channel = message["channel"]
                        send_bitcoin_price(channel)
                        send_dogecoin_price(channel)
                        send_litecoin_price(channel)

            time.sleep(4)
    else:
        print("Connection Failed")
示例#13
0
def main():

    args, err = Protocol.receiveParameters(sys.argv[1:])
    if err:
        Protocol.sendError("invalid arguments", args)
        return

    # prices will get the company's data
    prices = Prices()

    # Enter only if we will pricing with remote data
    if args["download_path"] != None:
        Protocol.sendStatus("starting download", args["code"])
        # Use this CSV file in the load step.
        mkdir(args["download_path"])
        args["filepath_data"] = prices.download(args["code"], args["start"],
                                                args["end"],
                                                args["download_path"], "Yahoo")
        Protocol.sendStatus("download ended", args["filepath_data"])

    # Load a downloaded CSV file.
    Protocol.sendStatus("loading csv", args["filepath_data"])
    prices.load(args["filepath_data"])

    # Check if prices loaded the CSV correctly.
    if not prices.isLoaded():
        Protocol.sendError("data not loaded")
        return

    # Check if data doesn't have any invalid value
    elif not prices.isValidData():
        Protocol.sendStatus("cleaning data")
        # If there are any wrong value, try to fix it.
        fixed = prices.cleanData()

        # Otherwise, we can handle this data.
        if not fixed:
            Protocol.sendError("invalid csv format", args["filepath_data"])
            return

    # Data is valid and is ready to process.
    else:
        Protocol.sendStatus("loaded", args["filepath_data"])

        # Plot the prices
        #filename = prices.getPlot()
        json_plot, _ = Plotter.timeSeries(prices.data.Date,
                                          High=prices.data.High,
                                          Low=prices.data.Low,
                                          Close=prices.data.Close)
        Protocol.sendStatus("plot generated", json_plot)

        Protocol.sendStatus("setting simulation params")

        # Initial price
        S0 = prices.getLastPrice()
        Protocol.sendStatus("setting initial price", S0)

        # Strike price
        K = float(args["strike_price"])
        Protocol.sendStatus("setting strike price", K)

        # Maturity time
        T = float(args["maturity_time"])
        Protocol.sendStatus("setting maturity time", T)

        # Simulations
        I = int(args["simulations"])
        Protocol.sendStatus("setting Monte Carlo simulations", I)

        # Riskless rate
        r = float(args["r"])
        Protocol.sendStatus("setting riskless rate", r)

        # Here we will price the option
        Protocol.sendStatus("starting simulation")

        # Calculate Volatility
        sigma = prices.getVolatility()
        Protocol.sendStatus("using volatility", sigma)

        # using the correct option type
        if args["option_type"] == "EU":
            option = EuropeanOptionPricing(S0, K, T, r, sigma, I)
            Protocol.sendStatus("using European Option")
        elif args["option_type"] == "USA":
            option = AmericanOptionPricing(S0, K, T, r, sigma, I)
            Protocol.sendStatus("using American Option")
        else:
            # European is the default option
            Protocol.sendError("wrong option type", args["option_type"])
            option = EuropeanOptionPricing(S0, K, T, r, sigma, I)
            Protocol.sendStatus("using European Option")
            args["option_type"] = "EU"

        # TODO ONLY BUY CALL
        Protocol.sendStatus("getting call option")
        results = option.getCallOption()
        """
        if args["option"] == "call":
            Protocol.sendStatus("getting call option")        
            result = option.getCallOption()
            
        elif args["option"] == "pull":
            Protocol.sendStatus("getting pull option")        
            result = option.getPullOption()
        """
        Protocol.sendStatus("simulation ended")

        # Build result

        if args["option_type"] == "EU":
            result_data = {
                "type": "EU",
                "result": {
                    "payoff": results[0],
                    "price": results[1],
                }
            }
        elif args["option_type"] == "USA":
            result_data = {
                "type": "USA",
                "result": {
                    "plot_data":
                    Plotter.americanOption(list(results[1]),
                                           list(results[0]))[1]
                }
            }

        Protocol.sendResult(json.dumps(result_data))
        sys.stdout.flush()
示例#14
0
from flask import Flask
from flask import request
from flask import Response
from flask_sslify import SSLify
from cheeseprice import getCheesePrice
from mortgage import Mortgage
from botutils import parse_message, send_message
from tokens import gipo_token, cheeze_token
from datetime import datetime, timedelta
from prices import Prices
from users import Users

prices_db = "prices.sqlite3"
users_db = "users.sqlite3"

p = Prices(prices_db)
p.create_tab()
u = Users(users_db)
u.create_tab()

app = Flask(__name__)
sslify = SSLify(app)


@app.route('/', methods=['POST', 'GET'])
def index():
    return '<h1>Buongiorno!!!</h1>'


@app.route('/gipo', methods=['POST', 'GET'])
def gipo_handler():
示例#15
0
        return np.exp(-1.0 * a) * payoff, np.mean(self.prices, axis=1)

    def getPullOption(self, recalculate=True):
        days = np.ceil(self.maturity_time * 365)

        T = np.linspace(0, 1, days) * (self.maturity_time)
        if recalculate:
            self.prices = self.simulateTrajectories()
        payoff = self.strike_price - np.mean(self.prices, axis=1)
        return np.exp(-1.0 * self.riskless_rate * T) * payoff, np.mean(
            self.prices, axis=1)


if __name__ == "__main__":
    from prices import Prices
    netflix = Prices()
    netflix.load("../../test/data/NFLX.csv")
    S0 = netflix.getLastPrice()
    K = 310
    T = 0.08333
    r = 0.05
    sigma = netflix.getVolatility()
    I = 10
    european_option = EuropeanOptionPricing(S0, K, T, r, sigma, I)
    american_option = AmericanOptionPricing(S0, K, T, r, sigma, I)

    print("==Option Parameters==")
    print("Test data:", "../../test/data/NFLX.csv")
    print("Initial price:", S0)
    print("Strike price:", K)
    print("Maturity time:", T, "[year]")
示例#16
0
class TraderPro(wrapper.EWrapper, client.EClient):
    """
    @Description:   Program designed as part of the requirement for MSF 597 at the Stuart School 
                    of Business.
    @Term:          Spring 2020
    @Student:       Ariwoola Abdulroqeeb
    
    """

    #tick_price_changed = QtCore.pyqtSignal(str)

    def __init__(self, window=None):
        wrapper.EWrapper.__init__(self)
        client.EClient.__init__(self, wrapper=self)
        #QtWidgets.QThread.__init__(self, None)

        self.reqMarketDataType(
            wrapper.MarketDataTypeEnum.DELAYED)  #Use delayed data
        self.nextValidOrderId = 1
        self.permId2ord = {}
        self.req_to_table_row = {}
        self.tracked_names = {}
        self.account_details = {}
        self.positions = {}
        self.open_orders = {}
        if window: self.window = window
        self.prices_history = Prices()
        self.portfolio_value_hist = {}
        self.req_to_strategy = {}
        self.strategies = {}

    def save_strategies(self):
        data = {}
        for key in self.strategies.keys():
            print('Halting: ', type(self.strategies.get(key)))
            try:
                strat = self.strategies.get(key)
                if strat:

                    strat.live = False
                    strat.broker = None
                    self.strategies[key] = strat

                    # dat = {}
                    # dat['symbol'] = strat.symbol
                    # dat['short_window'] = strat.short_window
                    # dat['long_window'] = strat.long_window
                    # dat['position'] = strat.position
                    # dat['pnl'] = strat.pnl
                    # dat['cost'] = strat.cost
                    # dat['trades'] = strat.trades
                    # dat['order_size'] = strat.order_size
                    # dat['live'] = strat.live
                    # dat['name'] = strat.name
                    # dat['strategy_type'] = strat.strategy_type
                    # data[key] = dat

            except:
                pass

        with open('strategies.pk', 'wb') as file:
            print(type(data))
            print('Saving: ', data)
            pickle.dump(self.strategies, file)
            self.prices_history.save_price_history()

    def load_strategies(self):
        try:
            with open('strategies.pk', 'rb') as file:
                self.strategies = pickle.load(file)
                for key, strategy in self.strategies.items():
                    strategy.live = True
                    strategy.broker = self
                    _thread = threading.Thread(target=strategy.run_strategy)
                    _thread.start()
                    self.strategies[key] = strategy
                    self.window.update_live_strategies_view()
            print('Existing strategies loaded: ', self.strategies)

        except Exception as ex:
            print('Error loading existing strategies: ', ex)
            self.strategies = {}

    @utils.iswrapper
    # ! [nextvalidid]
    def nextValidId(self, orderId: int):
        super().nextValidId(orderId)

        logging.debug("setting nextValidOrderId: %d", orderId)
        self.nextValidOrderId = orderId
        print("NextValidId:", orderId)
        self.window.log("setting nextValidOrderId: {}".format(orderId))
        self.getAccountDetails()
        self.reqManagedAccts()
        self.reqNewsProviders()
        self.register_news()

    def managedAccounts(self, accountsList: str):
        super().managedAccounts(accountsList)
        self.account = accountsList
        self.window.log("Account list:", accountsList)
        self.reqAccountUpdates(True, self.account)

    @utils.iswrapper
    # ! [updateaccountvalue]
    def updateAccountValue(self, key: str, val: str, currency: str,
                           accountName: str):
        super().updateAccountValue(key, val, currency, accountName)
        self.window.log("{} | {} | {} | {}".format("UpdateAccountValue. Key:",
                                                   key, "Value:", val,
                                                   "Currency:", currency,
                                                   "AccountName:",
                                                   accountName))

        if key in account_details_params:
            self.account_details[key] = val

        if key == 'NetLiquidation':
            self.portfolio_value_hist[datetime.datetime.now()] = val
            self.window.update_portfolio_hist_chart(self.portfolio_value_hist)

        #self.window.update_account_table(self.account_details)

    # ! [updateaccountvalue]

    @utils.iswrapper
    # ! [updateportfolio]
    def updatePortfolio(self, contract: wrapper.Contract, position: float,
                        marketPrice: float, marketValue: float,
                        averageCost: float, unrealizedPNL: float,
                        realizedPNL: float, accountName: str):
        super().updatePortfolio(contract, position, marketPrice, marketValue,
                                averageCost, unrealizedPNL, realizedPNL,
                                accountName)
        self.window.log("UpdatePortfolio.", "Symbol:", contract.symbol,
                        "SecType:", contract.secType, "Exchange:",
                        contract.exchange, "Position:", position,
                        "MarketPrice:", marketPrice, "MarketValue:",
                        marketValue, "AverageCost:", averageCost,
                        "UnrealizedPNL:", unrealizedPNL, "RealizedPNL:",
                        realizedPNL, "AccountName:", accountName)

        self.positions[contract.symbol] = {
            "Symbol": contract.symbol,
            "SecType": contract.secType,
            "Position": position,
            "MarketValue": marketValue,
            "AverageCost": averageCost,
            "UnrealizedPNL": unrealizedPNL,
            "RealizedPNL:": realizedPNL
        }
        self.window.update_positions_table(self.positions)

        if contract.symbol not in self.tracked_names:
            self.streamPrice(contract.symbol)
            self.requestContractDetails(contract.symbol)

    # ! [updateportfolio]

    @utils.iswrapper
    # ! [updateaccounttime]
    def updateAccountTime(self, timeStamp: str):
        super().updateAccountTime(timeStamp)
        self.window.log("UpdateAccountTime. Time:", timeStamp)
        self.account_details['last_updated'] = timeStamp

    # ! [updateaccounttime]

    @utils.iswrapper
    # ! [accountdownloadend]
    def accountDownloadEnd(self, accountName: str):
        super().accountDownloadEnd(accountName)
        self.window.log("AccountDownloadEnd. Account:", accountName)
        print('Final account details: ', self.account_details)

        if self.window:
            self.window.update_account_table(self.account_details)
            self.window.update_positions_table(self.positions)

        print(self.portfolio_value_hist)

    # ! [accountdownloadend]

    @utils.iswrapper
    # ! [error]
    def error(self, reqId: wrapper.TickerId, errorCode: int, errorString: str):
        super().error(reqId, errorCode, errorString)
        print("Error occured on req: {}-{}. Message: {}".format(
            reqId, errorCode, errorString))

    """
    Implements API functionalities for fetching
    """

    #Processing Contract Details
    @utils.iswrapper
    def contractDetails(self, reqId: int,
                        contractDetails: wrapper.ContractDetails):
        super().contractDetails(reqId, contractDetails)
        #my_utils.printinstance(contractDetails)
        self.window.log(contractDetails.longName)
        self.window.update_tick_table(self.req_to_table_row.get(reqId),
                                      1,
                                      contractDetails.longName,
                                      align_center=False)

    @utils.iswrapper
    def contractDetailsEnd(self, reqId: int):
        super().contractDetailsEnd(reqId)
        self.window.log("ContractDetailsEnd. ReqId: {}".format(reqId))

    #Streaming data -- All Last
    @utils.iswrapper
    def tickByTickAllLast(self, reqId: int, tickType: int, time: int,
                          price: float, size: int,
                          tickAtrribLast: wrapper.TickAttribLast,
                          exchange: str, specialConditions: str):
        super().tickByTickAllLast(reqId, tickType, time, price, size,
                                  tickAtrribLast, exchange, specialConditions)
        if tickType == 1:
            print("Last.", end='')
        else:
            print("AllLast.", end='')

        print(
            " ReqId:", reqId, "Time:",
            datetime.datetime.fromtimestamp(time).strftime("%Y%m%d %H:%M:%S"),
            "Price:", price, "Size:", size, "Exch:", exchange, "Spec Cond:",
            specialConditions, "PastLimit:", tickAtrribLast.pastLimit,
            "Unreported:", tickAtrribLast.unreported)

    @utils.iswrapper
    def realtimeBar(self, reqId: wrapper.TickerId, time: int, open_: float,
                    high: float, low: float, close: float, volume: int,
                    wap: float, count: int):
        self.window.log('Realtime bar called')
        super().realtimeBar(reqId, time, open_, high, low, close, volume, wap,
                            count)
        #print("RealTimeBar. TickerId:", reqId, wrapper.RealTimeBar(time, -1, open_, high, low, close, volume, wap, count))

    @utils.iswrapper
    def tickPrice(self, reqId: wrapper.TickerId, tickType: wrapper.TickType,
                  price: float, attrib: wrapper.TickAttrib):
        super().tickPrice(reqId, tickType, price, attrib)
        _row = self.req_to_table_row.get(reqId)

        if (ticktypes.get(int(tickType))) == 'Bid':
            self.window.update_tick_table(_row, 2, str(price))

        elif (ticktypes.get(int(tickType))) == 'Ask':
            self.window.update_tick_table(_row, 3, str(price))

        elif (ticktypes.get(int(tickType))) == 'Last':
            self.window.update_tick_table(_row, 4, str(price))
            _inv_names_key = {v: k for k, v in self.tracked_names.items()}

            self.prices_history.update_price_series(_inv_names_key.get(reqId),
                                                    price)
            print(_inv_names_key)

        elif (ticktypes.get(int(tickType))) == 'High':
            self.window.update_tick_table(_row, 5, str(price))

        elif (ticktypes.get(int(tickType))) == 'Low':
            self.window.update_tick_table(_row, 6, str(price))

        else:
            print('Unknown tickType: {}'.format(tickType))

        #self.window.update_ui()

    @utils.iswrapper
    def tickSize(self, reqId: wrapper.TickerId, tickType: wrapper.TickType,
                 size: int):
        super().tickSize(reqId, tickType, size)
        if (ticktypes.get(int(tickType))) == 'Volume':
            self.window.update_tick_table(self.req_to_table_row.get(reqId), 7,
                                          str(size))
            self.window.update_tick_table(self.req_to_table_row.get(reqId), 8,
                                          str('none'))

    @utils.iswrapper
    def tickString(self, reqId: wrapper.TickerId, tickType: wrapper.TickType,
                   value: str):
        pass

    """
    Placing Trades
    """

    @utils.iswrapper
    def openOrder(self, orderId: wrapper.OrderId, contract: wrapper.Contract,
                  order: wrapper.Order, orderState: wrapper.OrderState):
        super().openOrder(orderId, contract, order, orderState)

        self.open_orders[orderId] = {
            "ticker": contract.symbol,
            "action": order.action,
            "ordertype": order.orderType,
            "totalqty": order.totalQuantity,
            "lmtprice": order.lmtPrice,
            "status": orderState.status,
            "strategy": self.req_to_strategy.get(orderId)
        }

        order.contract = contract
        self.permId2ord[order.permId] = order

        print(self.open_orders)
        self.window.update_open_orders_table(self.open_orders)

    @utils.iswrapper
    def openOrderEnd(self):
        super().openOrderEnd()
        print("OpenOrderEnd")
        print(self.permId2ord)
        logging.debug("Received %d openOrders", len(self.permId2ord))
        self.window.log(self.open_orders)

        #app.disconnect()

    @utils.iswrapper
    def orderStatus(self, orderId: wrapper.OrderId, status: str, filled: float,
                    remaining: float, avgFillPrice: float, permId: int,
                    parentId: int, lastFillPrice: float, clientId: int,
                    whyHeld: str, mktCapPrice: float):
        super().orderStatus(orderId, status, filled, remaining, avgFillPrice,
                            permId, parentId, lastFillPrice, clientId, whyHeld,
                            mktCapPrice)
        print("OrderStatus. Id:", orderId, "Status:", status, "Filled:",
              filled, "Remaining:", remaining, "AvgFillPrice:", avgFillPrice,
              "PermId:", permId, "ParentId:", parentId, "LastFillPrice:",
              lastFillPrice, "ClientId:", clientId, "WhyHeld:", whyHeld,
              "MktCapPrice:", mktCapPrice)
        #app.disconnect()

    """
    Account summary operations
    """

    @utils.iswrapper
    def accountSummary(self, reqId: int, account: str, tag: str, value: str,
                       currency: str):
        super().accountSummary(reqId, account, tag, value, currency)
        self.window.log("{} | {} | {} | {}".format(
            "AccountSummary. ReqId: {}".format(reqId),
            "Account: {}".format(account), "Tag: {}".format(tag),
            "Value: {}".format(value), "Currency: {}".format(currency)))

    @utils.iswrapper
    def accountSummaryEnd(self, reqId: int):
        super().accountSummaryEnd(reqId)
        self.window.log("AccountSummaryEnd. ReqId:", reqId)
        #app.disconnect()

    '''
    News
    '''

    def register_news(self):
        contract = wrapper.Contract()
        contract.symbol = "BRFG:BRFG_ALL"
        contract.secType = "NEWS"
        contract.exchange = "BRFG"

        self.reqMktData(1009, contract, "mdoff,292", False, False, [])

    @utils.iswrapper
    #! [tickNews]
    def tickNews(self, tickerId: int, timeStamp: int, providerCode: str,
                 articleId: str, headline: str, extraData: str):
        print("TickNews. TickerId:", tickerId, "TimeStamp:", timeStamp,
              "ProviderCode:", providerCode, "ArticleId:", articleId,
              "Headline:", headline, "ExtraData:", extraData)

    #! [tickNews]

    @utils.iswrapper
    #! [newsProviders]
    def newsProviders(self, newsProviders: wrapper.ListOfNewsProviders):
        print("NewsProviders: ")
        for provider in newsProviders:
            print("NewsProvider.", provider)

    #! [newsProviders]

    @utils.iswrapper
    #! [newsArticle]
    def newsArticle(self, reqId: int, articleType: int, articleText: str):
        print("NewsArticle. ReqId:", reqId, "ArticleType:", articleType,
              "ArticleText:", articleText)

    #! [newsArticle]

    def streamPrice(self, ticker):

        if ticker not in self.tracked_names.keys():

            #Logging and Setting Valid ID
            self.window.log('New ticker submitted', self.tracked_names)
            self.nextValidOrderId = self.nextValidOrderId + 1

            self.tracked_names[ticker] = self.nextValidOrderId
            self.reqMarketDataType(wrapper.MarketDataTypeEnum.DELAYED)
            contract = my_utils.get_USD_stock_contract(ticker)

            self.reqMktData(self.nextValidOrderId, contract, "", False, False,
                            [])
            _current_row = self.window.ui.tick_table.rowCount()
            self.window.ui.tick_table.insertRow(_current_row)

            self.req_to_table_row[self.nextValidOrderId] = _current_row
            self.window.ui.tick_table.setVerticalHeaderItem(
                _current_row,
                QtWidgets.QTableWidgetItem(
                    str(self.req_to_table_row.get(self.nextValidOrderId))))
            self.window.ui.tick_table.setItem(
                self.req_to_table_row.get(self.nextValidOrderId), 0,
                QtWidgets.QTableWidgetItem(contract.symbol))

        else:
            self.window.ui.statusBar().showMessage(
                'Stream Price: {} is already tracked'.format(ticker), 3000)

    def orderContract(self,
                      ticker,
                      quantity,
                      action='BUY',
                      order_type='MKT',
                      lmt_price=0,
                      strategy='Discretionary'):

        self.nextValidOrderId = self.nextValidOrderId + 1
        contract = my_utils.get_USD_stock_contract(ticker)
        order = wrapper.Order()
        order.action = action
        order.orderType = order_type
        if order.orderType == 'LMT': order.lmtPrice = lmt_price
        order.totalQuantity = quantity

        self.placeOrder(self.nextValidOrderId, contract, order)
        self.req_to_strategy[self.nextValidOrderId] = strategy

    def getAccountDetails(self):
        self.nextValidOrderId = self.nextValidOrderId + 1
        self.reqAccountSummary(self.nextValidOrderId, "All",
                               AccountSummaryTags.AllTags)

    def requestContractDetails(self, ticker):
        ticker = ticker.upper()
        contract = my_utils.get_USD_stock_contract(ticker)
        self.reqContractDetails(self.nextValidOrderId, contract)
示例#17
0
class Bot:

    MODE_REAL = 1
    MODE_SIMULATED = 0

    def __init__(self,
                 wallet,
                 ticker=None,
                 strategy=None,
                 start_date=None,
                 mode=MODE_SIMULATED):
        self._on_off = True
        self._ticker = ticker
        self._strategy = strategy
        self._wallet = wallet
        self._prices = Prices(self._ticker)
        if start_date != None:
            self._prices.setDatePoint(start_date)
        self._mode = mode

    def start(self):
        while self._on_off:
            stock_info = self._wallet.getStock(self._ticker)
            price = self._prices.getNextPrice()
            signal = self._strategy.evalueate(stock_info, price, self._wallet)

            if signal['action'] != Operation.NEUTRAL:
                operation = Operation(signal['action'], self._ticker,
                                      price['open'], signal['qnt'])

                if self._validateOperation(operation):
                    self._operate(operation)

            self._on_off = self._prices.hasNext()

    def _operate(self, operation):
        self._wallet.update(operation)
        print(operation)

    def _validateOperation(self, operation):
        operation_data = operation.getOperationData()

        if operation_data['type'] == Operation.BUY:
            wallet_ressources = self._wallet.getRessources()
            operation_cost = operation_data['qnt'] * operation_data['price']

            if wallet_ressources >= operation_cost:
                return True
            else:
                return False

        elif operation_data['type'] == Operation.SELL:
            stock = self._wallet.getStock(operation_data['ticker'])

            if stock['qnt'] > operation_data['qnt']:
                return True
            else:
                return False

        else:
            return False
示例#18
0
class ProfitChecker:
    __metaclass__ = ABCMeta
    
    def __init__(self):
        self.d = Downloader(wait=0.0)
        self.m = Manufacturing()
        self.p = Prices()
        self.g = Groups()
        
        self.results = {}
        
    def start(self):
        self.all_valid_ids = self.m.fetch_all_valid_ids()
        
        self.m.load_data()
        self.p.load_data()
        self.g.load_data()
        self.p.warm_up(self.all_valid_ids)
    
    
    def check_manufacturing_cost(self, type_id):
        requirements = self.m.get_full_requirements_dict(type_id)
    
        requirement_ids = requirements.keys()
        prices = self.p.get_component_prices(requirement_ids, price_type=PriceType.SELL_PERCENTILE)
        
        cost = 0
        for requirement_id in requirement_ids:
            cost += requirements[requirement_id] * prices[requirement_ids.index(requirement_id)]
    
        return cost
    
    def check_reprocessing_value(self, type_id):
        requirements = self.m.get_full_reprocessing_dict(type_id)
    
        requirement_ids = requirements.keys()
        prices = self.p.get_component_prices(requirement_ids, price_type=PriceType.SELL_PERCENTILE)
        
        value = 0
        for requirement_id in requirement_ids:
            value += requirements[requirement_id] * prices[requirement_ids.index(requirement_id)]
    
        return value

    def check_profit_bulk(self, type_ids=None):
        if not type_ids:
            type_ids = self.all_valid_ids
            
        f = open('type_ids.txt', 'w')
        for type_id in type_ids:
            f.write(str(type_id) + "\n")
        f.close()
        
        final_ids = self.filter_type_ids(type_ids)
            
        for type_id in final_ids:
            self.check_profit(type_id)

    @abstractmethod
    def filter_type_ids(self, type_ids):
        pass

    @abstractmethod
    def check_profit(self, type_id):
        pass
    
    def add_basics_to_result(self, result, type_id):
        component = self.m.data[type_id]
        
        group_name = "Unknown"
        if component.group_id in self.g.data:
            group_name = self.g.data[component.group_id]
            
        result['name'] = component.name
        result['group'] = group_name
        result['volume'] = component.volume
            
        return result
    
    def write_output(self, filename):
        type_ids = self.results.keys()
        
        if len(type_ids) > 0:
            f = open(filename, 'w')
            
            
            
            if type(self.results[type_ids[0]]) == type([]):
                # We are writing a list of results within each type_id
                column_names = self.results[type_ids[0]][0].keys()
                column_names.sort()
                
                for key in column_names:
                    f.write(key + ",")
                f.write('\n')
                
                type_ids = self.results.keys()
                type_ids.sort()
                
                for type_id in type_ids:
                    for entry in self.results[type_id]:
                        for key in column_names:
                            f.write(str(entry[key]) + ",")
                        f.write('\n')
            else:
                # We have a single result for each type_id
                column_names = self.results[type_ids[0]].keys()
                column_names.sort()
                
                for key in column_names:
                    f.write(key + ",")
                f.write('\n')
                
                type_ids = self.results.keys()
                type_ids.sort()
                
                for type_id in type_ids:
                    for key in column_names:
                        f.write(str(self.results[type_id][key]) + ",")
                    f.write('\n')
        
            f.close()
        
        print "Calculated profitability for " + str(len(type_ids)) + " items!"

    @abstractmethod
    def filter_results(self):
        pass

    def finish(self, filename):
        self.write_output(filename)
        self.p.finish()
        self.m.finish()
        self.g.finish()
示例#19
0
            base + dt.timedelta(days=x) for x in range(1, 1 + len(prices))
        ]
        dates = [dt.datetime.strftime(date, "%Y-%m-%d") for date in date_list]
        plot_data = {
            "prices": {
                "x": dates,
                "y": prices
            },
            "payoff": {
                "x": dates,
                "y": payoff
            }
        }
        return dumps(plot_data), plot_data

    @staticmethod
    def europeanOption(price, payoff):
        """
        """
        pass


if __name__ == '__main__':
    #main()
    netflix = Prices()
    netflix.load("../../test/data/NFLX.csv")
    p1, d1 = Plotter.timeSeries(netflix.data.Date,
                                High=netflix.data.High,
                                Low=netflix.data.Low,
                                Close=netflix.data.Close)
    print(p1)