Oh no! Where's the JavaScript?
Your Web browser does not have JavaScript enabled or does not support JavaScript. Please enable JavaScript on your Web browser to properly view this Web site, or upgrade to a Web browser that does support JavaScript.
Articles

etrade api sample place buy order

Here is a complete Python script to place a buy order using the E*TRADE API.

 

Authenticates using OAuth1
Gets the account ID
Places a market buy order for a stock (e.g., MSFT)


Step 1: Install Required Libraries

E*TRADE API requires OAuth 1.0 authentication. Install the necessary packages:

pip install requests requests-oauthlib

Step 2: Python Code to Place a Buy Order

Replace API keys with your actual E*TRADE Consumer Key & Secret.

import requests
from requests_oauthlib import OAuth1

# 🔹 Replace these with your E*TRADE API credentials
CONSUMER_KEY = "your_consumer_key"
CONSUMER_SECRET = "your_consumer_secret"
ACCESS_TOKEN = "your_access_token"
ACCESS_SECRET = "your_access_secret"

# 🔹 Base API URLs
BASE_URL = "https://apisb.etrade.com" # Use "https://api.etrade.com" for live trading
ACCOUNT_LIST_URL = f"{BASE_URL}/v1/accounts/list"
PLACE_ORDER_URL = f"{BASE_URL}/v1/accounts/{'{account_id}'}/orders/place"

# 🔹 Setup OAuth1 authentication
auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET)

# Step 1: Get Account ID
response = requests.get(ACCOUNT_LIST_URL, auth=auth)
if response.status_code == 200:
 accounts = response.json()
 account_id = accounts["AccountListResponse"]["Accounts"]["Account"][0]["accountId"]
 print(f"✅ E*TRADE Account ID: {account_id}")
else:
 print("❌ Error fetching account details:", response.json())
 exit()

# Step 2: Define Market Order for MSFT
order_payload = {
 "PlaceOrderRequest": {
 "orderType": "EQ", # Equity order
 "clientOrderId": "123456789", # Unique order ID
 "orderAction": "BUY",
 "quantity": 5, # Buying 5 shares
 "symbol": "MSFT",
 "priceType": "MARKET", # Market order
 "orderTerm": "GOOD_FOR_DAY",
 "marketSession": "REGULAR"
 }
}

# Step 3: Place the Order
response = requests.post(PLACE_ORDER_URL.format(account_id=account_id), json=order_payload, auth=auth)

# Step 4: Check Response
if response.status_code == 200:
 order_info = response.json()
 print("✅ Order Placed Successfully:", order_info)
else:
 print("❌ Order Placement Failed:", response.json())

🔹 How It Works

1️⃣ Authenticates using OAuth1
2️⃣ Fetches the account ID
3️⃣ Places a Market Buy Order for MSFT (5 shares)


✅ Enhancements

  • Stop-Loss & Limit Orders:
    "priceType": "LIMIT",
    "limitPrice": 400.00
    
  • TradingView Webhook Integration for Automated Trading
  • Logging System for tracking trades

 

caa January 28 2025 28 reads 0 comments Print

0 comments

Leave a Comment

Please Login to Post a Comment.
  • No Comments have been Posted.

Sign In
Not a member yet? Click here to register.
Forgot Password?
Users Online Now
Guests Online 3
Members Online 0

Total Members: 14
Newest Member: Frank_nKansas