Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import collections
- import datetime
- import glob
- import simplejson
- import time
- import traceback
- from ib.ext.CommissionReport import CommissionReport
- from ib.ext.Contract import Contract
- from ib.ext.ExecutionFilter import ExecutionFilter
- from ib.opt import ibConnection, message
- import ftp_utils
- class EphemeralIBSession(object):
- def __init__(self):
- self.conn = ibConnection(clientId=17)
- self.conn.register(self.update_next_valid_id, "NextValidId")
- self.conn.register(self.update_account_value_handler, "UpdateAccountValue")
- self.conn.register(self.update_executions_handler, "ExecDetails")
- self.conn.register(self.update_commissions_handler, "CommissionReport")
- def init(self):
- self.account = collections.OrderedDict()
- self.fills = []
- self.fill_by_exec_id = {}
- self.next_order_id = None
- self.reset_last_updated()
- def reset_last_updated(self):
- self.last_update_ts = time.time()
- def time_since_last_update(self):
- return time.time() - self.last_update_ts
- def to_dict(self):
- res = collections.OrderedDict()
- res["account"] = self.account
- res["fills"] = self.fills
- return res
- def update_next_valid_id(self, msg):
- self.next_order_id = msg.orderId
- self.reset_last_updated()
- def update_account_value_handler(self, msg):
- self.account[msg.key] = collections.OrderedDict(msg.items())
- if msg.currency is not None:
- try:
- self.account[msg.key]["value"] = float(self.account[msg.key]["value"])
- except:
- pass
- self.reset_last_updated()
- def update_executions_handler(self, msg):
- fill = {
- "ticker": msg.contract.m_symbol,
- "currency": msg.contract.m_currency,
- "price": msg.execution.m_price,
- "sqty": msg.execution.m_shares*(+1 if msg.execution.m_side == "BOT" else -1),
- "time": msg.execution.m_time,
- "exch": msg.execution.m_exchange,
- "order_id": msg.execution.m_permId,
- "exec_id": msg.execution.m_execId,
- "sec_type": msg.contract.m_secType,
- "fees": 0.0, # to be filled out by commissions callback
- "fees_currency": None # to be filled out by commissions callback
- }
- self.fills.append(fill)
- self.fill_by_exec_id[fill["exec_id"]] = fill
- self.reset_last_updated()
- def update_commissions_handler(self, msg):
- self.fill_by_exec_id[msg.commissionReport.m_execId]["fees"] = msg.commissionReport.m_commission
- self.fill_by_exec_id[msg.commissionReport.m_execId]["fees_currency"] = msg.commissionReport.m_currency
- self.reset_last_updated()
- def run(self):
- self.init()
- try:
- self.conn.connect()
- start_time = time.time()
- while self.next_order_id is None:
- if time.time() - start_time >= 10:
- raise Exception("unable to connect")
- time.sleep(0.1)
- self.conn.reqAccountUpdates(1, "")
- self.conn.reqExecutions(1, ExecutionFilter())
- except:
- traceback.print_exc()
- else:
- while self.time_since_last_update() <= 2:
- time.sleep(0.1)
- finally:
- self.conn.disconnect()
- if __name__ == '__main__':
- sess = EphemeralIBSession()
- sess.run()
- results = sess.to_dict()
- if results["account"]:
- with open("{}.json".format(datetime.date.today().strftime("%Y%m%d")), "w") as f:
- simplejson.dump(results, f, indent=2)
- ftp_utils.upload_to_data(glob.glob("*.json"))
- dates = sorted(set(x["time"].split(" ")[0] for x in results["fills"]))
- print("dates fetched: {}".format(dates))
- raw_input("Press any key to continue...")
- import os
- import paramiko
- import traceback
- def upload(filenames, destination, remove_original=True):
- if not hasattr(filenames, '__iter__'):
- filenames = [filenames]
- if len(filenames) == 0:
- return
- host = "billtable.com"
- port = 22
- transport = paramiko.Transport((host, port))
- transport.connect(username=username, password=password)
- sftp = paramiko.SFTPClient.from_transport(transport)
- try:
- for fname in filenames:
- filepath = "{}/{}".format(destination, os.path.basename(fname))
- sftp.put(fname, filepath)
- print("copied {!r} to {!r}".format(fname, filepath))
- if remove_original:
- os.unlink(fname)
- except:
- traceback.print_exc()
- finally:
- sftp.close()
- transport.close()
- def upload_to_data(filenames):
- upload(filenames, "/root/projects/tb/data")
- def upload_to_nc(filenames):
- upload(filenames, "/root/projects/tb/populate/source")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement