├── .gitattributes ├── LICENSE └── ts.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Roman Paolucci 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ts.py: -------------------------------------------------------------------------------- 1 | from ibapi.wrapper import EWrapper 2 | from ibapi.client import EClient 3 | from ibapi.contract import Contract 4 | from ibapi.order import Order 5 | from ibapi.utils import iswrapper 6 | import threading 7 | import abc 8 | import time 9 | 10 | 11 | class Controller(EWrapper, EClient): 12 | 13 | @iswrapper 14 | def error(self, reqId, errorCode, errorString): 15 | print(errorString) 16 | 17 | @iswrapper 18 | def connectAck(self): 19 | print("\n[Connected]") 20 | self.connected = True 21 | 22 | @iswrapper 23 | def nextValidId(self, orderId): 24 | self.order_id = orderId 25 | 26 | @iswrapper 27 | def tickPrice(self, reqId, tickType, price, attrib): 28 | super().tickPrice(reqId, tickType, price, attrib) 29 | # Responsible for setting the last price reference field for a system 30 | if reqId == 1000: 31 | if tickType == 4: # Last Trading Price 32 | self.nasdaq_last_price = price 33 | 34 | def getNewOrderId(self): 35 | self.order_id += 1 36 | return self.order_id 37 | 38 | def __init__(self): 39 | EWrapper.__init__(self) 40 | EClient.__init__(self, wrapper=self) 41 | 42 | # Reference Fields 43 | self.connected = False 44 | self.order_id = 0 45 | self.nasdaq_last_price = 0 46 | 47 | 48 | class TradingSystem(abc.ABC): 49 | 50 | @abc.abstractmethod 51 | def trading_signal(self): 52 | pass 53 | 54 | @abc.abstractmethod 55 | def execute_trade(self): 56 | pass 57 | 58 | @abc.abstractmethod 59 | def run_system(self): 60 | pass 61 | 62 | def __init__(self, controller, system_id, request_ids): 63 | self.controller = controller 64 | self.system_id = system_id 65 | self.request_ids = request_ids 66 | thread = threading.Thread(target=self.run_system) 67 | thread.start() 68 | 69 | 70 | class NasdaqTradingSystem(TradingSystem): 71 | 72 | def trading_signal(self): 73 | if not self.active_order: 74 | print('System ', self.system_id, ': Buy Executed') 75 | self.execute_trade('BOT') 76 | else: 77 | print('System ', self.system_id, ': Sell Executed') 78 | self.execute_trade('SLD') 79 | 80 | def execute_trade(self, position_type): 81 | if position_type == 'BOT': 82 | # Enter a long position 83 | order = Order() 84 | order.action = "BUY" 85 | order.orderType = "MKT" 86 | order.totalQuantity = 1 87 | self.buy_price = self.controller.nasdaq_last_price # For Proft Ref 88 | self.instance_order_id = self.controller.getNewOrderId() # For system order reference (potential cancellation etc...) 89 | self.active_order = True 90 | self.controller.placeOrder(self.instance_order_id, self.contract, order) 91 | elif position_type == 'SLD': 92 | # Check for profit and potentially execute a sell order 93 | if self.buy_price < self.controller.nasdaq_last_price: 94 | order = Order() 95 | order.action = "SELL" 96 | order.orderType = "MKT" 97 | order.totalQuantity = 1 98 | self.buy_price = 0 99 | self.instance_order_id = self.controller.getNewOrderId() # For system order reference (potential cancellation etc...) 100 | self.active_order = False 101 | self.controller.placeOrder(self.instance_order_id, self.contract, order) 102 | else: 103 | print('System ', self.system_id, ': No Profit, Holding') 104 | # Hold another 10 seconds 105 | pass 106 | 107 | def run_system(self): 108 | while(True): 109 | if self.controller.connected and self.controller.nasdaq_last_price == 0: 110 | self.controller.reqMktData(self.request_ids['MktDataId'], self.contract, "", False, False, []) 111 | if not self.controller.nasdaq_last_price == 0: # Implies Live Data 112 | print('System ', self.system_id, ': Trading Signal Call') 113 | self.trading_signal() 114 | time.sleep(10) 115 | 116 | def __init__(self, controller, system_id, request_ids): 117 | self.buy_price = 0 118 | self.active_order = False 119 | self.instance_order_id = 0 120 | self.contract = Contract() 121 | self.contract.symbol = "NQ" 122 | self.contract.localSymbol = "NQH1" 123 | self.contract.secType = "FUT" 124 | self.contract.exchange = "GLOBEX" 125 | self.contract.currency = "USD" 126 | super().__init__(controller, system_id, request_ids) 127 | 128 | def main(): 129 | controller = Controller() 130 | nasdaq_request_ids = {'MktDataId': 1000} 131 | nasdaq_trading_system = NasdaqTradingSystem(controller, 'Nasdaq A', nasdaq_request_ids) 132 | controller.connect('127.0.0.1', 7497, 0) 133 | controller.reqMarketDataType(1) 134 | controller.reqAllOpenOrders() 135 | controller.run() 136 | 137 | 138 | if __name__ == "__main__": 139 | main() 140 | --------------------------------------------------------------------------------