E*TRADE Developer Platform api sample program
ETRADE's Developer Platform API allows automated trading, account management, and market data retrieval. Below is a sample Python program to authenticate with ETRADE and place a trade (buy stock).
🔹 Steps to Place a Trade via E*TRADE API
- Register for API Access on E*TRADE Developer Portal.
- Obtain OAuth1 Keys (Consumer Key & Secret).
- Authenticate using OAuth1 to get an access token.
- Place an Order for a sample stock (e.g., Microsoft - MSFT).
Step 1: Install Dependencies
E*TRADE API uses OAuth 1.0, so install required libraries:
pip install requests requests-oauthlib
Step 2: Python Code to Authenticate & Place a Trade
This script:
- Authenticates with OAuth 1.0.
- Fetches Account Information (for placing an order).
- Places a Market Order for MSFT.
import requests
from requests_oauthlib import OAuth1
# E*TRADE API Keys (Replace with your credentials)
CONSUMER_KEY = "your_consumer_key"
CONSUMER_SECRET = "your_consumer_secret"
ACCESS_TOKEN = "your_access_token"
ACCESS_SECRET = "your_access_secret"
# E*TRADE API URLs
BASE_URL = "https://apisb.etrade.com" # Sandbox URL (Use https://api.etrade.com for Live)
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: Place a Market Order for MSFT (Buy 5 Shares)
order_payload = {
"PlaceOrderRequest": {
"orderType": "EQ", # Equity Order
"clientOrderId": "123456789", # Unique ID for Order
"orderAction": "BUY",
"quantity": 5,
"symbol": "MSFT",
"priceType": "MARKET", # Market Order
"orderTerm": "GOOD_FOR_DAY",
"marketSession": "REGULAR"
}
}
response = requests.post(PLACE_ORDER_URL.format(account_id=account_id), json=order_payload, auth=auth)
# Step 3: 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 This Works
- Authenticates using OAuth1.
- Fetches your Account ID.
- Sends a Market Order for 5 shares of MSFT.
✅ Enhancements
- Stop-Loss & Take-Profit:
"stopPrice": 390.0 # Stop-loss at $390
- Trailing Stop Orders for dynamic risk management.
- Paper Trading Mode with Sandbox API before Live Trading.
No Comments have been Posted.