Qqqetf Test

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

import ibapi

from ibapi.client import EClient


from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import Order
import time

class IBApi(EWrapper, EClient):


def __init__(self, wrapper):
EClient.__init__(self, wrapper)
EWrapper.__init__(self)

class MyTradingApp(EWrapper):
def __init__(self, client_id):
self.app = IBApi(self)
self.client_id = client_id
self.current_price = None

def start(self):
self.app.connect("127.0.0.1", 7497, clientId=self.client_id)
self.app.run()

def stop(self):
self.app.disconnect()

def nextOrderId(self, orderId):


self.app.nextValidOrderId = orderId
self.place_order()

def place_order(self):
contract = self.create_contract("QQQ")
order = self.create_order('BUY', 1)
# Place buy order
self.app.placeOrder(self.app.nextValidOrderId, contract, order)

def create_contract(self, symbol, sec_type='STK', exchange='SMART',


currency='USD'):
contract = Contract()
contract.symbol = symbol
contract.secType = sec_type
contract.exchange = exchange
contract.currency = currency
return contract

def create_order(self, action, quantity):


order = Order()
order.action = action
order.totalQuantity = quantity
order.orderType = 'MKT' # Market Order
return order

def error(self, reqId, errorCode, errorString):


print("Error:", reqId, errorCode, errorString)
def connectionClosed(self):
print("Connection closed.")

def tickPrice(self, reqId, tickType, price, attrib):


if tickType == 4: # TickType 4 corresponds to "Last Price"
self.current_price = price
self.sell_order(price) # Call the sell_order method when new
price is received

def fetch_market_data(self):
contract = self.create_contract("QQQ")
self.app.reqMktData(1, contract, "", False, False, [])

def sell_order(self, current_price):


if current_price:
target_profit = 1.02 * current_price # 2% profit
stop_loss = 0.98 * current_price # 2% loss

contract = self.create_contract("QQQ")
order = self.create_order('SELL', 1)

print(f"Current Price: {current_price}")

if current_price >= target_profit or current_price <=


stop_loss:
# Place sell order
self.app.placeOrder(self.app.nextValidOrderId, contract,
order)
print("Sell order placed.")
self.stop()

if __name__ == "__main__":
YOUR_CLIENT_ID = 1 # Replace this with your actual client ID
trading_app = MyTradingApp(YOUR_CLIENT_ID)
trading_app.start()
trading_app.fetch_market_data() # Request market data
time.sleep(10) # Wait for 10 seconds before stopping the app (adjust
as needed)
trading_app.stop()

You might also like