Torn Stocks Info

Fetch Torn stocks information using API and display adjusted 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.6
// @description  Fetch Torn stocks information using API and display adjusted 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 adjusted profit/loss percentage considering the sale fee
    function calculateAdjustedPercentage(boughtPrice, currentPrice) {
        const rawPercentage = ((currentPrice - boughtPrice) / boughtPrice) * 100;
        const adjustedPercentage = (rawPercentage - 0.1).toFixed(2);
        return adjustedPercentage;
    }

    // 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, stockInfo) {
        // Clear the content of the list container before updating
        listContainer.innerHTML = '';

        for (const stockId in stockInfo) {
            const stockData = stockInfo[stockId];

            const listItem = document.createElement('div');
            listItem.textContent = `${stockData.name}: ${stockData.adjustedProfitLossPercentage}%`;
            listItem.style.marginBottom = '5px';

            if (stockData.adjustedProfitLossPercentage < 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;
    }

    // Function to fetch and update stock information
    function fetchAndUpdateStockInfo() {
        const apiUrl = `https://api.torn.com/user/?selections=stocks&key=${getApiKey()}`;
        const stockInfo = GM_getValue('tornStockInfo', {});

        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 adjusted profit/loss percentage considering the sale fee
                            const currentPrice = detailedStockInfo.stocks[stockId].current_price;
                            const adjustedProfitLossPercentage = calculateAdjustedPercentage(boughtPrice, currentPrice);

                            // Update stock information
                            stockInfo[stockId] = {
                                name: detailedStockInfo.stocks[stockId].name,
                                adjustedProfitLossPercentage: adjustedProfitLossPercentage
                            };

                            // Update the list container with stock information
                            updateListContainer(listContainer, stockInfo);

                            // Store updated stock information
                            GM_setValue('tornStockInfo', stockInfo);
                        },
                        onerror: function(error) {
                            console.error('Error making second API request:', error);
                        }
                    });
                }
            },
            onerror: function(error) {
                console.error('Error making API request:', error);
            }
        });
    }

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

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