[转载]python 自动卖出京东黄金

梦浪的小虾米
2021-11-03 / 0 评论 / 1,250 阅读 / 正在检测是否收录...

上个月看到虎友买卖京东积存金的,我也随手买了点。

金价一直在 385 上下波动,我在 381 元时买入了两次,然后 388 左右卖出(并不推荐这样做,投机短线交易不可取),都小赚了一点点。

老是看金价或者关注自动推送(是的,我还简单弄了个钉钉机器人监控价格哈哈)的话还是有点累,就想着拿 python 写个自动交易卖出的。看了请求加密一堆参数也懒得分析了,selenium 开干。

大致如下,自行改造吧。简单写写,写的比较乱。只做了卖出,买入还是谨慎些,没考虑做。

需要 Python3 环境,需要修改的地方就是那些 xxxxxxxxxxxxxxx。

建议单步调试代码,看一下大致逻辑再使用。或者仅供参考,自己重新实现。

20210201 11:00 成功自动卖出

import json
import sys
import traceback

from selenium import webdriver
import time, requests


def getLatestPrice():
    url = 'https://api.jdjygold.com/gw/generic/hj/h5/m/latestPrice?reqData=%7B%7D'
    response = requests.get(url=url)
    print(response)
    print(response.headers)
    jsonRes = json.loads(response.content)
    price = float(jsonRes['resultData']['datas']['price'])
    print(time.strftime("%Y-%m-%d %H:%M:%S  ", time.localtime()), '最新价', price)
    return price


def openJdjyGold():
    webdriverPath = "C:\Program Files\Google\Chrome\Application\chromedriver.exe"  # webdriver路径

    activityUrl = "https://m.jdjygold.com/finance-gold/newgold/index"
    sellGoldUrl = "https://m.jdjygold.com/finance-gold/newgold/sellGold/"  # 如果直接去卖金的地方,可能来不及注入cookie

    browser = webdriver.Chrome(executable_path=webdriverPath)
    browser.set_window_size('400', '700')
    browser.get(activityUrl)
    browser.delete_all_cookies()
    # 读取cookie写入。第一次使用时注释掉这段,手动登陆一次后用下面的更新存储。自行改造啦。
    with open('cookies.json', 'r', encoding='utf-8') as f:
        listCookies = json.loads(f.read())
        for cookie in listCookies:
            browser.add_cookie({
                'domain': cookie['domain'],
                'name': cookie['name'],
                'value': cookie['value'],
                'path': '/',
                'expires': None
            })
    # 更新一下文件存储的cookie
    cookies = browser.get_cookies()
    jsonCookies = json.dumps(cookies)
    with open('cookies.json', 'w') as f:
        f.write(jsonCookies)
    browser.get(sellGoldUrl)
    return browser


def sellGold():
    print('开始卖出')
    browser = openJdjyGold()
    time.sleep(2)
    # 已经到卖出的页面了
    # 全部卖出的文字按钮,可以优化为 find_elements_by_class_name
    sellAllBtn = browser.find_elements_by_css_selector(
        "#app > div > div.inputBox > div.input_content > div.input-row.flex.flex-align-center > p")
    sellAllBtn[0].click()  # 点一下卖全部,填入数量
    time.sleep(0.5)
    # 勾选我已阅读xxx
    checkIHaveReadRules = browser.find_element_by_class_name("check-icon")
    checkIHaveReadRules.click()
    time.sleep(0.5)
    # 卖出页面下方的 立即卖出
    startSellBtn = browser.find_element_by_class_name("jrm-common-btn")
    startSellBtn.click()
    time.sleep(2)
    # 然后是输入密码,找到全部密码按键存到dict
    passwordBtnDict = {}
    allPasswordBtn = browser.find_elements_by_class_name("sys-itemW")
    for btnItem in allPasswordBtn:
        if btnItem.text != '':  # 有两个按键用不上
            passwordBtnDict[btnItem.text] = btnItem
    payPassword = "xxxxxxxxxxxxxxx"  # 支付密码,不要泄露了.............................
    for bitPwd in payPassword:
        passwordBtnDict[bitPwd].click()
    # 输入完最后一位,就自动确定了
    # 然后忘了还有没有进一步的确定。。。。。。
    time.sleep(10)
    sendDingtalkNotify('完成卖出')
    browser.quit()


def autoSellGold(expectPrice):
    while True:
        try:
            latestPrice = getLatestPrice()
            if latestPrice > expectPrice:
                sendDingtalkNotify('''最新价{}元/g,高于预期的{}元/g,准备全部卖出'''.format(latestPrice, expectPrice))
                sellGold()
                sys.exit(0)
            else:
                print('未达预期', expectPrice, ',不卖')
        except Exception as e:
            traceback.print_exc()
            sendDingtalkNotify('京东积存金自动交易出错,需要处理')
            sys.exit(1)
        finally:
            time.sleep(30)


def sendDingtalkNotify(msg):
    print('sendDingTalkMsg', msg)
    url = 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxxxxxx'
    headers = {
        'Content-Type': 'application/json'
    }
    data = {
        "msgtype": "text",
        "text": {
            "content": "[bot]" + msg + "@xxxxxxxxxxxxxxx"
        },
        "at": {
            "atMobiles": ["xxxxxxxxxxxxxxx"],
            "isAtAll": False
        }
    }
    response = requests.post(url=url, headers=headers, json=data)
    print(response.content)


if __name__ == '__main__':
    buyPrice = 383  # 买入价格,如果想不亏的话,需要的涨幅应该是手续费0.3%
    minimumPrice = round(buyPrice * 1.003, 3)
    print('''{}买入的话,最少应该{}才能卖'''.format(buyPrice, minimumPrice))
    expectPrice = minimumPrice * 1.01  # 期望价格,可以自己改一下
    autoSellGold(expectPrice)
0

评论 (0)

取消