需求: 交易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)