Node.js Code for Bar Trading
Below is the Node.js code for automating bar trading using E-Trade API.
const axios = require('axios'); const moment = require('moment'); // Replace with your E-Trade API credentials const CONSUMER_KEY = "your_consumer_key"; const CONSUMER_SECRET = "your_consumer_secret"; const ACCESS_TOKEN = "your_access_token"; const ACCESS_TOKEN_SECRET = "your_access_secret"; const BASE_URL = "https://api.etrade.com/v1"; // Use sandbox URL for testing // Define your stock and expiration logic const STOCK_SYMBOL = "VIDEO"; // Replace with actual symbol const CONTRACT_EXPIRATION = moment().add(7, 'days'); // 1-week expiration // Function to get market open time function getMarketOpen() { return moment().hour(9).minute(30).second(0).millisecond(0); } // Function to get market close time function getMarketClose() { return moment().hour(16).minute(0).second(0).millisecond(0); } // Function to place a market buy order async function buyStock() { const url = `${BASE_URL}/accounts/${STOCK_SYMBOL}/orders/place`; const data = { symbol: STOCK_SYMBOL, orderType: "MARKET", priceType: "MARKET", quantity: 1, orderAction: "BUY" }; const response = await axios.post(url, data, { headers: { Authorization: `Bearer ${ACCESS_TOKEN}` } }); return response.data; } // Function to place a market sell order async function sellStock() { const url = `${BASE_URL}/accounts/${STOCK_SYMBOL}/orders/place`; const data = { symbol: STOCK_SYMBOL, orderType: "MARKET", priceType: "MARKET", quantity: 1, orderAction: "SELL" }; const response = await axios.post(url, data, { headers: { Authorization: `Bearer ${ACCESS_TOKEN}` } }); return response.data; } // Trading Logic async function executeBarTrading() { const today = moment().day(); // 0 = Sunday, 1 = Monday, ..., 5 = Friday const currentTime = moment(); if (today === 1 && currentTime.isSameOrAfter(getMarketOpen())) { console.log("Buying stock at market open..."); const buyResponse = await buyStock(); console.log(buyResponse); } while (moment().isBefore(CONTRACT_EXPIRATION)) { await new Promise(resolve => setTimeout(resolve, 60000)); // Check every minute if (moment().day() === 5 && moment().isSameOrAfter(getMarketClose())) { console.log("Selling stock at market close..."); const sellResponse = await sellStock(); console.log(sellResponse); break; } } } // Run the trading function executeBarTrading();