daily pastebin goal
47%
SHARE
TWEET

fvc

a guest Nov 24th, 2017 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import xlwings as wb
  2. import time
  3. from datetime import datetime, timedelta
  4. from multiprocessing import JoinableQueue as queue
  5. import pandas as pd
  6. from threading import Thread
  7. from sqlalchemy import create_engine
  8. import asyncio
  9. from ib_insync import *
  10.  
  11. db_queue = queue()
  12. strat_queue = queue()
  13. now = datetime.now()
  14.  
  15. def to_db(symb):
  16.     global db_queue
  17.     data = pd.DataFrame(columns=('Date', 'Close_price'))
  18.     engine = create_engine('mysql://root:B@CKT3ST3Rfr@mew0rk@localhost:3306/stock_base', echo=True)
  19.  
  20.     while True:
  21.         d = db_queue.get()
  22.         data =  data.append({'Date':d[0], 'Close_price':d[1]}, ignore_index=True)
  23.         db_queue.task_done()
  24.  
  25.         if len(data) == 2:
  26.             data = data.set_index(pd.to_datetime(data['Date']))
  27.             data =  data.drop(data.columns[0], axis=1)
  28.             #print("\n\tEntering the Table into database *** for *** \n",data, "\n")
  29.  
  30.             data.to_sql(name=symb, con=engine, if_exists='append', index=False)
  31.             data = pd.DataFrame(columns=('Date', 'Close_price'))
  32.         time.sleep(2)
  33.  
  34. @asyncio.coroutine
  35. def strat_MA(window,sym):
  36.     print("started strategy thread")
  37.     buffer = pd.DataFrame(columns=['close'])
  38.  
  39.     while len(buffer) <= window:
  40.         n = strat_queue.get()
  41.         buffer = buffer.append({'close': n}, ignore_index=True)
  42.  
  43.  
  44.     ib = IB()
  45.     ib.connect('127.0.0.1', 7496, clientId=5)
  46.     contract = Stock(sym, 'AEB', 'EUR')
  47.     ib.qualifyContracts(contract)
  48.  
  49.     while True:
  50.         n = strat_queue.get()
  51.         buffer = buffer.append({'close': n}, ignore_index=True)
  52.         MA = buffer.rolling(window).mean()
  53.         Position = ib.reqPositions()
  54.  
  55.         if buffer['close'].iloc[-1] < (.01 * MA['close'].iloc[-1]) and len(Position) == 0:
  56.             order = MarketOrder('BUY', 10)
  57.             ib.placeOrder(contract, order)
  58.             print ("buy order generated")
  59.  
  60.         if buffer['close'].iloc[-1] > (.01 * MA['close'].iloc[-1]) and len(Position) > 0:
  61.             order = MarketOrder('SELL', 10)
  62.             ib.placeOrder(contract, order)
  63.             print("sell order generated")
  64.  
  65. def filter_per_min(val, ts, lts):
  66.  
  67.     epoch = datetime(now.year, now.month, now.day)
  68.     result = epoch + timedelta(days=ts)
  69.     result = result.replace(microsecond=0,second=0)
  70.  
  71.     if result > lts:
  72.         lts = result
  73.         a = [result, val]
  74.         print(result, "price:", val)
  75.         db_queue.put(a)
  76.         strat_queue.put(val)
  77.     return lts
  78.  
  79.  
  80. ############################################################################
  81. b = 1
  82. while b == 1:
  83.     sym = input('Enter the symbol: ')
  84.     print("\nEnter 0 to confirm your symbol as: ",sym)
  85.     b = int(input(''))
  86. window = int(input('Enter window length for MA strategy: '))
  87. nw = now.replace(microsecond=0,second=0)
  88. start =  time.time()
  89. db = Thread(name='db',target=to_db,args=(sym,))
  90. dstrat = Thread(name='MA', target=strat_MA,args=(window, sym,))
  91. db.start()
  92. dstrat.start()
  93.  
  94.  
  95. while True:
  96.     try:
  97.         wb.Book(r'C:\Users\Administrator\Desktop\Datasets\RT_feed.xlsx')
  98.         time.sleep(1)
  99.         a = wb.Range('B1').value
  100.         b = wb.Range('E1').value
  101.     except Exception:
  102.         print("-----Waiting for RTD server response----")
  103.         time.sleep(1)
  104.  
  105.     try:
  106.         nw = filter_per_min(a, b, nw)
  107.     except Exception:
  108.         print("-----Waiting1 for RTD server response----")
  109.         time.sleep(1)
RAW Paste Data
Top