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 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 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
})();