okx欧易自动交易

需求:  交易PEPE的时候,发现在一段时间内价格一直在一个范围内波动,但时刻的盯盘又很累,

于是想着是不是可以开发一个自动交易的小程序帮我24盯盘交易。后来发现了欧易提供了API接口

实现: 自定义的涨幅%点之后,自动卖出,并低位买进,然后挂在一个点位卖出
缺点:只适合固定范围内波动,如果一直涨或者跌就不适合了 (需要能连接到国外网络的服务器,因为okx服务再国外)
项目源代码: python-okx: 欧易(okx)自动交易
如需帮助联系:1078804404@qq.com

import time
from datetime import datetime

import okx.Account as Account
import okx.MarketData as MarketData
import okx.Trade as Trade
from decimal import Decimal
import math
import json

# API 初始化
api_key = "xxxx"
secret_key = "xxxxx"
passphrase = "xxxxx"
instId = "PEPE-USDT"
rate = 0.96
flag = "0"  # 实盘:0 , 模拟盘:1

marketDataAPI = MarketData.MarketAPI(flag=flag, debug=False)
accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag, debug=False)
tradeAPI = Trade.TradeAPI(api_key, secret_key, passphrase, False, flag)


def basicMessagePrint():
    result = accountAPI.get_account_balance(ccy='PEPE,BTC,USDT')
    data = result['data'][0]
    totalEq = data['totalEq']
    print("=====================资金用户===========================")
    print('总资产:{} 美元'.format(round(float(totalEq), 2)))
    details = data['details']
    for item in details:
        print('币种: {}, 总权益: {}, 可用余额: {},可用保证金:{}'.format(item['ccy'], round(float(item['eq']), 2),
                                                                        round(float(item['cashBal']), 2),
                                                                        round(float(item['availEq']), 2)))
    # 获取当前账户交易手续费费率
    result = accountAPI.get_fee_rates(
        instType="SPOT",
        instId=instId
    )
    print("币种: {} 费率: maker {} taker {}".format(instId, result['data'][0]['maker'], result['data'][0]['taker']))


def buy(availBuy, lastPrice):
    # 计算小数位
    num = Decimal(lastPrice)
    precision = abs(num.as_tuple().exponent)
    # 低价买入
    lowPrice = float(lastPrice) * rate
    lowPriceStr = format(lowPrice, f'.{precision}f')

    buyNumber = math.floor(availBuy / lowPrice)

    # # limit order
    result = tradeAPI.place_order(
        instId=instId,
        tdMode="cash",
        clOrdId="b15",
        side="buy",
        ordType="limit",
        px=lowPriceStr,
        sz=buyNumber
    )
    if result["code"] == "0":
        print("买入成功 最后成交价{} 买入价格{} 买入个数{}".format(lastPrice, lowPriceStr, buyNumber))
        data = {"type": instId, "order_id": result["data"][0]["ordId"], "lastPrice": lastPrice, "buyPrice": lowPriceStr,
                "buyNumber": buyNumber}
        with open("/web/logs/okex/buy.json", "w") as file:
            json.dump(data, file)
    else:
        print("Unsuccessful order request,error_code = ", result["data"][0]["sCode"], ", Error_message = ",
              result["data"][0]["sMsg"])


def sell(availSell):
    print("prepare to sell", availSell)
    with open("/web/logs/okex/buy.json", "r") as file:
        data = json.load(file)

        if data['type'] == instId:
            lastPrice = data['lastPrice']
            buyPrice = data['buyPrice']
            result = tradeAPI.place_order(
                instId=instId,
                tdMode="cash",
                side="sell",
                ordType="limit",
                px=lastPrice,
                sz=availSell
            )
            if result["code"] == "0":
                data = {"type": instId, "order_id": result["data"][0]["ordId"],
                        "buyPrice": buyPrice,
                        "sellPrice": lastPrice,
                        "sellNumber": availSell}
                with open("/web/logs/okex/planSell.json", "a") as file1:
                    json.dump(data, file1)
            else:
                print("Unsuccessful order request,error_code = ", result["data"][0]["sCode"], ", Error_message = ",
                      result["data"][0]["sMsg"])
        else:
            print("当前币种与buy.json中币种不一致")


def handle():
    # 获取单个产品行情信息
    result = marketDataAPI.get_ticker(
        instId=instId
    )
    code = result['code']
    print(datetime.now(), "=====================行情信息===========================")
    lastPrice = None
    if code == "0":
        item = result['data'][0]
        lastPrice = item['last']
        print(
            "{}: 最新成交价:{} 24小时最高价:{}  最低价{} UTC0时开盘价{}".format(instId, item['last'], item['high24h'],
                                                                                item['low24h'], item['sodUtc0']))
    else:
        print("ERROR MESSAGE:", result['msg'])

    result = accountAPI.get_max_avail_size(
        instId=instId,
        tdMode="cash"
    )
    # 	交易模式 # cross:全仓 isolated:逐仓 cash:非保证金
    # print(result)
    availBuy = math.floor(float(result['data'][0]['availBuy']))
    availSell = math.floor(float(result['data'][0]['availSell']))
    print('{}: 可买{} USDT 可卖{}'.format(instId, availBuy, availSell))

    if availBuy > 1:
        buy(availBuy, lastPrice)

    if availSell > 1:
        sell(availSell)

    # result = accountAPI.get_account_balance(ccy='PEPE')
    # data = result['data'][0]
    # details = data['details']
    # item = details[0]
    # print(item)
    # print('币种: {}, 未实现盈亏: {}'.format(item['ccy'], item['upl']))


if __name__ == '__main__':
    try:
        # # 查看持仓信息
        # result1 = accountAPI.get_positions()
        # # result = accountAPI.get_positions_history()
        # print(result1)
        # # 查看账户账单详情 (近七日内)
        # result1 = accountAPI.get_account_bills()
        # print(result1)
        basicMessagePrint()
    except Exception as e1:
        print("error message:", e1)
    finally:
        i = 1
        while True:
            try:

                handle()
            except Exception as e:
                print("error message", e)
                try:
                    marketDataAPI = MarketData.MarketAPI(flag=flag, debug=False)
                    accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag, debug=False)
                    tradeAPI = Trade.TradeAPI(api_key, secret_key, passphrase, False, flag)
                except Exception as e1:
                    pass

            print("执行第", i, "次")

            i = i + 1
            time.sleep(60 * 2)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

centos604

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值