import datetime as datetime
from okx.app import OkxSWAP
from pprint import pprint
import os
import sys
sys.path.append(os.path.dirname( os.path.dirname(os.path.abspath(__file__))))
from dotenv import load_dotenv
load_dotenv()
# 永续合约交易账户需要秘钥
key = os.getenv("OKX_API_KEY")
secret = os.getenv("OKX_API_SECRET")
passphrase = os.getenv("OKX_API_PASSPHRASE")
# 实盘:0,虚拟盘:1
# flag = '1'
# 使用http和https代理,proxies={'http':'xxxxx','https:':'xxxxx'},与requests中的proxies参数规则相同
proxies = {}
# 转发:需搭建转发服务器,可参考:https://github.com/pyted/okx_resender
proxy_host = None
okxSWAP = OkxSWAP(
key=key, secret=secret, passphrase=passphrase, proxies=proxies, proxy_host=proxy_host)
account = okxSWAP.account
## 3. 同步 市价开仓
trade = okxSWAP.trade
# 执行成功回调
def success_callback(information):
# mystool.SendMsgToQiyeWeixin("永续合约交易成功", str(information))
print("下单成功")
# 执行错误回调
def error_callback(information):
# mystool.SendMsgToQiyeWeixin("永续合约交易失败", str(information))
print("下单失败")
# 下单函数
# coin_name 币种名称
# level 杠杆倍数
# amount 金额
# UpOrDown 买涨还是买跌 1 买涨 0 买跌
def OrderContract(coin_name,amount,level,UpOrDown):
if UpOrDown == 1:
posSide = 'long'
else:
posSide = 'short'
# 设置callback和errorback
open_market4 = trade.open_market(
instId=coin_name, # 合约名称
tdMode='isolated', # 持仓方式 isolated:逐仓 cross:全仓
posSide=posSide, # 持仓方向 long:多单 short:空单
lever=level, # 杠杆倍数
openMoney=amount, # 开仓金额 开仓金额openMoney和开仓数量quantityCT必须输入其中一个 优先级:quantityCT > openMoney
quantityCT=0, # 开仓数量 注意:quantityCT是合约的张数,不是货币数量
tag='', # 订单标签
clOrdId='b15', # 客户自定义订单ID
meta={}, # 向回调函数中传递的参数字典
callback=success_callback, # 开仓成功触发的回调函数
errorback=error_callback, # 开仓失败触发的回调函数
)
pprint(open_market4)
## 3. 同步 市价平仓
# 平仓函数
def close_order(coin_name):
# 设置callback和errorback
close_market4 = okxSWAP.trade.close_market(
instId=coin_name , # 产品
tdMode='isolated', # 持仓方式 isolated:逐仓 cross:全仓
posSide='long', # 持仓方向 long:多单 short:空单
quantityCT='all', # 平仓数量,注意:quantityCT是合约的张数,不是货币数量
tag='', # 订单标签
clOrdId='', # 客户自定义订单ID
meta={}, # 向回调函数中传递的参数字典
callback=success_callback, # 开仓成功触发的回调函数
errorback=error_callback, # 开仓失败触发的回调函数
)
pprint(close_market4)
OrderContract('SHIB-USDT-SWAP',10,2,0)