Python Code for Bar Trading
import requests
import datetime
import time
# Replace with your E-Trade API credentials
CONSUMER_KEY = “your_consumer_key”
CONSUMER_SECRET = “your_consumer_secret”
ACCESS_TOKEN = “your_access_token”
ACCESS_TOKEN_SECRET = “your_access_secret”
BASE_URL = “https://api.etrade.com/v1” # Use sandbox URL for testing
# Define your stock and expiration logic
STOCK_SYMBOL = “VIDEO” # Replace with actual symbol
CONTRACT_EXPIRATION = datetime.datetime.now() + datetime.timedelta(days=7) # 1-week expiration
# Function to get market open time
def get_market_open():
now = datetime.datetime.now()
return now.replace(hour=9, minute=30, second=0, microsecond=0)
# Function to get market close time
def get_market_close():
now = datetime.datetime.now()
return now.replace(hour=16, minute=0, second=0, microsecond=0)
# Function to place a market buy order
def buy_stock():
url = f”{BASE_URL}/accounts/{STOCK_SYMBOL}/orders/place”
data = {
“symbol”: STOCK_SYMBOL,
“orderType”: “MARKET”,
“priceType”: “MARKET”,
“quantity”: 1, # Adjust as needed
“orderAction”: “BUY”
}
response = requests.post(url, json=data, headers={“Authorization”: f”Bearer {ACCESS_TOKEN}”})
return response.json()
# Function to place a market sell order
def sell_stock():
url = f”{BASE_URL}/accounts/{STOCK_SYMBOL}/orders/place”
data = {
“symbol”: STOCK_SYMBOL,
“orderType”: “MARKET”,
“priceType”: “MARKET”,
“quantity”: 1, # Adjust as needed
“orderAction”: “SELL”
}
response = requests.post(url, json=data, headers={“Authorization”: f”Bearer {ACCESS_TOKEN}”})
return response.json()
# Trading Logic
def execute_bar_trading():
today = datetime.datetime.today().weekday() # 0 = Monday, 4 = Friday
current_time = datetime.datetime.now()
if today == 0 and current_time >= get_market_open():
print(“Buying stock at market open…”)
buy_response = buy_stock()
print(buy_response)
while datetime.datetime.now() < CONTRACT_EXPIRATION:
time.sleep(60) # Check every minute
if datetime.datetime.now().weekday() == 4 and datetime.datetime.now() >= get_market_close():
print(“Selling stock at market close…”)
sell_response = sell_stock()
print(sell_response)
break
# Run the trading function
execute_bar_trading()