Hello World

这个是标题,但是为什么要有标题

这个是子标题,但是为什么要有子标题

python连接okx查询自己的持仓【量化交易】

 

需要安装ccxt

以下代码在jupyter中运行

需要去app中获取自己的apiKey、secret、password,才能查到自己的个人持仓情况

根据自己的代理设置proxies

 

import ccxt
import pandas as pd
import time
from IPython.display import clear_output
import traceback
from datetime import datetime

exchange = ccxt.okex({
    'apiKey': 'xxx',
    'secret': 'xxx',
    "password":"xxx",
    'timeout': 30000,
    'enableRateLimit': True,
    "proxies":{
        "http":"http://127.0.0.1:10809",
        "https":"http://127.0.0.1:10809",
    }
})


# 设置中文列名
cn_columns = {
    'instId': '名称',
    'entryPrice': '入场价格',
    'markPx': '标记价格',
    'liqPx': '清算价格',
    'unrealizedPnl': '收益',
    'percentage': '收益率'
}
all_df = []
while 1:
    ratio = 7.2755
    try:
        res = exchange.fetchBalance()
        balance = res["total"]["USDT"] * ratio
        df = pd.DataFrame([{**item["info"],**item}  for item in exchange.fetchPositions()])
        if df.shape[0]: # 有持仓 显示当前仓位情况
            imr = df["imr"].apply(lambda x:"%.2f%%"% (float(x) /  res["total"]["USDT"] * 100))
            df = df[cn_columns.keys()].rename(columns=cn_columns)
            df['时间'] = datetime.now().strftime('%H:%M:%S')
            df["当前金额"] = balance
            df["清算价格"] = df["清算价格"].astype(float).round(2)
            df["收益率"] = df["收益率"].apply(lambda x: "%.2f%%"%float(x))
            df["仓位占比"] = imr
            all_df = [df] + all_df
            all_df = all_df[:10]
            clear_output(wait=True)
            display(pd.concat(all_df))
        else:  # 无持仓 显示自选仓位情况
            datas = []
            for d in ["BTC/USDT","ETH/USDT","SOL/USDT"]:
                datas.append(exchange.fetch_ticker(symbol=d))
            df = pd.DataFrame(datas)[["symbol","datetime","last"]]
            df['datetime'] = pd.to_datetime(df['datetime']) + pd.Timedelta(hours=8)
            df['datetime'] = df['datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')
            df["当前金额"] = balance
            clear_output(wait=True)
            display(df)
    except:
        traceback.print_exc()
        break

 

 

运行结果:

 

 

# 设置中文列名
cn_columns = {
'instId': '名称',
'entryPrice': '入场价格',
'markPx': '标记价格',
'liqPx': '清算价格',
'unrealizedPnl': '收益',
'percentage': '收益率'
}
all_df = []
while 1:
ratio = 7.2755
try:
res = exchange.fetchBalance()
balance = res["total"]["USDT"] * ratio
df = pd.DataFrame([{**item["info"],**item} for item in exchange.fetchPositions()])
if df.shape[0]: # 有持仓 显示当前仓位情况
imr = df["imr"].apply(lambda x:"%.2f%%"% (float(x) / res["total"]["USDT"] * 100))
df = df[cn_columns.keys()].rename(columns=cn_columns)
df['时间'] = datetime.now().strftime('%H:%M:%S')
df["当前金额"] = balance
df["清算价格"] = df["清算价格"].astype(float).round(2)
df["收益率"] = df["收益率"].apply(lambda x: "%.2f%%"%float(x))
df["仓位占比"] = imr
all_df = [df] + all_df
all_df = all_df[:10]
clear_output(wait=True)
display(pd.concat(all_df))
else: # 无持仓 显示自选仓位情况
datas = []
for d in ["BTC/USDT","ETH/USDT","SOL/USDT"]:
datas.append(exchange.fetch_ticker(symbol=d))
df = pd.DataFrame(datas)[["symbol","datetime","last"]]
df['datetime'] = pd.to_datetime(df['datetime']) + pd.Timedelta(hours=8)
df['datetime'] = df['datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')
df["当前金额"] = balance
clear_output(wait=True)
display(df)
except:
traceback.print_exc()
break

posted on 2024-12-18 20:13  swuxyj  阅读(33)  评论(0编辑  收藏  举报

导航

Hello World