Mathieu2301 / TradingView-API

📈 Get real-time stocks from TradingView
1.6k stars 350 forks source link

Paper trading API #122

Closed brandonros closed 2 years ago

brandonros commented 2 years ago
import 'dotenv/config'
import fetch from 'node-fetch'
import TradingView from '@mathieuc/tradingview'

const placeOrder = async (sessionId, payload) => {
  const response = await fetch('https://papertrading.tradingview.com/trading/place/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Cookie': `sessionid=${sessionId}`,
      'Origin': 'https://www.tradingview.com',
      'Referer': 'https://www.tradingview.com/',
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
    },
    body: JSON.stringify(payload)
  })
  if (response.status !== 200) {
    console.log(await response.text())
    throw new Error(`Invalid response status: ${response.status}`)
  }
  const responseBody = await response.json()
  return responseBody
}

const run = async () => {
  // register unhandled rejection handler
  process.on('unhandledRejection', (reason, promise) => {
    console.error({
      reason,
      promise
    })
    process.exit(1)
  })
  // tradingview login (so quotes aren't delayed)
  const username = process.env.TRADINGVIEW_USERNAME
  const password = process.env.TRADINGVIEW_PASSWORD
  const rememberSession = true
  const loginResult = await TradingView.loginUser(username, password, rememberSession)
  // spawn tradingview client
  const client = new TradingView.Client({
    token: loginResult.session
  })
  console.log(loginResult)
  // place order
  await placeOrder(loginResult.session, {"symbol":"CME_MINI:ES1\u0021", "side":"buy", "type":"market", "qty":1})
  await placeOrder(loginResult.session, {"symbol":"CME_MINI:ES1\u0021", "side":"sell", "type":"market", "qty":1})
}

run()
monkeyhucker62 commented 6 months ago

how do you close position?