Torn Stocks Info

Fetch Torn stocks information using API and display profit/loss percentage as a list in the middle of the screen or top right corner

目前為 2024-02-16 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Torn Stocks Info
// @namespace    http://tampermonkey.net/
// @version      1.3
// @description  Fetch Torn stocks information using API and display profit/loss percentage as a list in the middle of the screen or top right corner
// @author       You
// @match        https://www.torn.com/*
// @grant        GM_xmlhttpRequest
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_addStyle
// ==/UserScript==

(function() {
    'use strict';

    // Function to prompt the user for their API key
    function promptForApiKey() {
        const apiKey = prompt('Please enter your Torn API key:');
        if (apiKey) {
            GM_setValue('tornApiKey', apiKey);
        } else {
            alert('Invalid API key. Please refresh the page and try again.');
        }
    }

    // Function to calculate profit/loss percentage
    function calculatePercentage(boughtPrice, currentPrice) {
        const percentage = ((currentPrice - boughtPrice) / boughtPrice) * 100;
        return percentage.toFixed(2);
    }

    // Function to create and update the list container
    function createListContainer() {
        const listContainer = document.createElement('div');
        listContainer.id = 'tornStockList';
        listContainer.style.position = 'fixed';
        listContainer.style.padding = '10px';
        listContainer.style.background = 'black';
        listContainer.style.color = 'white';
        listContainer.style.borderRadius = '5px';
        listContainer.style.zIndex = '1000';

        // Check if the current page is the stocks page
        const isStocksPage = window.location.href.includes('https://www.torn.com/page.php?sid=stocks');
        if (isStocksPage) {
            listContainer.style.top = '50%'; // Adjusted position
            listContainer.style.right = '5px'; // Adjusted position
            listContainer.style.transform = 'translateY(-50%)'; // Center vertically
        } else {
            listContainer.style.top = '10px'; // Adjusted position
            listContainer.style.right = '10px'; // Adjusted position
        }

        document.body.appendChild(listContainer);

        return listContainer;
    }

    // Function to update the list container with stock information
    function updateListContainer(listContainer, stockName, profitLossPercentage) {
        const listItem = document.createElement('div');
        listItem.textContent = `${stockName}: ${profitLossPercentage}%`;
        listItem.style.marginBottom = '5px';

        if (profitLossPercentage < 0) {
            listItem.style.color = 'red';
        } else {
            listItem.style.color = 'green';
        }

        listContainer.appendChild(listItem);
    }

    // Function to get the stored API key or prompt the user for a new one
    function getApiKey() {
        let apiKey = GM_getValue('tornApiKey');
        if (!apiKey) {
            promptForApiKey();
            apiKey = GM_getValue('tornApiKey');
        }
        return apiKey;
    }

    // URL for the API request to get stock information
    const apiUrl = `https://api.torn.com/user/?selections=stocks&key=${getApiKey()}`;

    // Create or get the list container
    let listContainer = document.getElementById('tornStockList');
    if (!listContainer) {
        listContainer = createListContainer();
    }

    // Make the API request and update values every minute
    function fetchData() {
        GM_xmlhttpRequest({
            method: 'GET',
            url: apiUrl,
            onload: function(response) {
                const stockData = JSON.parse(response.responseText).stocks;

                // Extract stock ID and bought price
                for (const stockId in stockData) {
                    const boughtPrice = stockData[stockId].transactions[Object.keys(stockData[stockId].transactions)[0]].bought_price;

                    // URL for the second API request to get detailed stock information
                    const secondApiUrl = `https://api.torn.com/torn/?selections=stocks&key=${getApiKey()}&stock_id=${stockId}&bought_price=${boughtPrice}`;

                    // Make the second API request
                    GM_xmlhttpRequest({
                        method: 'GET',
                        url: secondApiUrl,
                        onload: function(secondResponse) {
                            const detailedStockInfo = JSON.parse(secondResponse.responseText);

                            // Calculate profit/loss percentage
                            const currentPrice = detailedStockInfo.stocks[stockId].current_price;
                            const profitLossPercentage = calculatePercentage(boughtPrice, currentPrice);

                            // Update the list container with stock information
                            updateListContainer(listContainer, detailedStockInfo.stocks[stockId].name, profitLossPercentage);
                        },
                        onerror: function(error) {
                            console.error('Error making second API request:', error);
                        }
                    });
                }
            },
            onerror: function(error) {
                console.error('Error making API request:', error);
            }
        });
    }

    // Initial fetch and schedule updates every minute
    fetchData();
    setInterval(fetchData, 60000); // Update every minute
})();