-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathibProgram3.1.py
More file actions
205 lines (164 loc) · 6.61 KB
/
ibProgram3.1.py
File metadata and controls
205 lines (164 loc) · 6.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
from datetime import datetime
from ibapi import order
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import *
import threading
import time
import sys
def redirectStdoutToFile():
print('This message will be displayed on the screen.')
original_stdout = sys.stdout # Save a reference to the original standard output
original_stderr = sys.stderr # Save a reference to the original standard error
f = open('output-'+str(datetime.now().strftime("%Y%m%d-%H%M%S"))+'.log', 'w', encoding='utf-8')
sys.stdout = f # Change the standard output to the file we created.
sys.stderr = f # Change the standard error to the file we created.
print('This message will be written to a file.')
# sys.stdout = original_stdout # Reset the standard output to its original value
class IBapi(EWrapper, EClient):
lastAction = None
contract = None
lastBuyOrderId = None
lastSellOrderId = None
def __init__(self):
EClient.__init__(self, self)
def nextValidId(self, orderId: int):
super().nextValidId(orderId)
self.nextorderId = orderId
print('The next valid order id is: ', self.nextorderId)
def createContract(self):
#Create contract
self.contract = Contract() # Creates a contract object from the import
# US
self.contract.symbol = "VT" # Sets the ticker symbol
self.contract.secType = "STK" # Defines the security type as stock
self.contract.currency = "USD" # Currency is US dollars
# In the API side, NASDAQ is always defined as ISLAND in the exchange field
self.contract.exchange = "SMART"
# # Australia
# self.contract.symbol = "FPH" # Sets the ticker symbol
# self.contract.secType = "STK" # Defines the security type as stock
# self.contract.currency = "AUD" # Currency is US dollars
# # In the API side, NASDAQ is always defined as ISLAND in the exchange field
# self.contract.exchange = "ASX"
def createOpenningOrders(self):
#Create order object - Long
orderBuy = Order()
orderBuy.action = 'BUY'
orderBuy.totalQuantity = 100
orderBuy.orderType = "TRAIL"
# orderBuy.trailStopPrice = 340.09
# orderBuy.lmtPriceOffset = 1.00
orderBuy.auxPrice = 0.20 # Try 0.80 next
orderBuy.tif = "DAY"
# orderBuy.outsideRth = True
orderBuy.orderId = app.nextorderId
self.lastBuyOrderId = orderBuy.orderId
app.nextorderId += 1
orderBuy.ocaGroup = "myOcaGroup" + str(orderBuy.orderId)
orderBuy.ocaType = 1
orderBuy.transmit = True
#Create order object - Short
orderSell = Order()
orderSell.action = 'SELL'
orderSell.totalQuantity = 100
orderSell.orderType = "TRAIL"
# orderSell.trailStopPrice = 339.66
# orderSell.lmtPriceOffset = 1.00
orderSell.auxPrice = 0.20 # Try 0.80 next
orderSell.tif = "DAY"
# orderSell.outsideRth = True
orderSell.orderId = app.nextorderId
app.lastSellOrderId = orderSell.orderId
app.nextorderId += 1
orderSell.ocaGroup = orderBuy.ocaGroup
orderSell.ocaType = 1
orderSell.transmit = True
# #Place orders
app.placeOrder(orderBuy.orderId, self.contract, orderBuy)
app.placeOrder(orderSell.orderId, self.contract, orderSell)
app.lastAction = "OPEN"
print("--- Created opening orders buy/sell: ", self.lastAction, self.lastBuyOrderId, "/", self.lastSellOrderId)
return
def orderStatus(self, orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice):
print('orderStatus - orderid:', orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice)
print('lastAction:', self.lastAction, " lastBuyOrderId:", self.lastBuyOrderId, " lastSellOrderId:", self.lastSellOrderId )
# Create new positions if no active position is open
if self.lastAction == "CLOSE" and remaining == 0 and status == "Filled" and (orderId == self.lastBuyOrderId or orderId == self.lastSellOrderId):
self.createOpenningOrders()
# After Long
elif self.lastAction == "OPEN" and remaining == 0 and status == "Filled" and orderId == self.lastBuyOrderId :
#Create order object
orderSell = Order()
orderSell.action = 'SELL'
orderSell.totalQuantity = 100
orderSell.orderType = "TRAIL LIMIT"
orderSell.trailStopPrice = avgFillPrice - 0.10
orderSell.lmtPriceOffset = 0.20
orderSell.auxPrice = 0.20
orderSell.orderId = self.nextorderId
self.lastBuyOrderId = None
self.lastSellOrderId = orderSell.orderId
orderSell.tif = "GTC"
orderSell.outsideRth = True
self.nextorderId += 1
orderSell.transmit = True
print('--- Decided to', orderSell.action)
# time.sleep(5)
self.placeOrder(orderSell.orderId, self.contract, orderSell)
self.lastAction = "CLOSE"
print("--- Submitted:",orderSell.action, orderSell.orderId)
# After Short
elif self.lastAction == "OPEN" and remaining == 0 and status == "Filled" and orderId == self.lastSellOrderId :
#Create order object
orderBuy = Order()
orderBuy.action = 'BUY'
orderBuy.totalQuantity = 100
orderBuy.orderType = "TRAIL LIMIT"
orderBuy.trailStopPrice = avgFillPrice + 0.10
orderBuy.lmtPriceOffset = 0.20
orderBuy.auxPrice = 0.20
orderBuy.orderId = self.nextorderId
self.lastBuyOrderId = orderBuy.orderId
self.lastSellOrderId = None
orderBuy.tif = "GTC"
orderBuy.outsideRth = True
self.nextorderId += 1
orderBuy.transmit = True
print('--- Decided to', orderBuy.action)
# time.sleep(5)
self.placeOrder(orderBuy.orderId, self.contract, orderBuy)
self.lastAction = "CLOSE"
print("--- Submitted:",orderBuy.action, orderBuy.orderId)
else:
print("--- Nothing to do. Will wait for next order update.\n\n")
def openOrder(self, orderId, contract, order, orderState):
print('openOrder id:', orderId, contract.symbol, contract.secType, '@', contract.exchange, ':', order.action, order.orderType, order.totalQuantity, orderState.status)
def execDetails(self, reqId, contract, execution):
print('Order Executed: ', reqId, contract.symbol, contract.secType, contract.currency, execution.execId, execution.orderId, execution.shares, execution.lastLiquidity, execution)
def run_loop():
app.run()
redirectStdoutToFile()
print("Creating IB API connection")
app = IBapi()
app.connect('127.0.0.1', 7497, 123)
# currentTime = app.reqCurrentTime
# print(currentTime)
app.nextorderId = None
#Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()
#Check if the API is connected via orderid
while True:
if isinstance(app.nextorderId, int):
print('connected')
print()
break
else:
print('waiting for connection')
# time.sleep(1)
app.createContract()
app.createOpenningOrders()
# app.disconnect()
# ADD Stop for short at $5.00 loss