Loading ...

期货网格python

Author: 顺为量化, Date: 2021-02-21 15:04:19
Tags:


'''backtest
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_OKCoin","currency":"BTC_USD"}]
'''

import time

operation_currency = []
operation_currency_two = ''
base_account = []

contract_type = 'quarter'

usdt_value = {
    'BTC': 0.01,
    'LTC': 1,
    'ETH': 0.1,
    'ETC': 10,
    'XRP': 100,
    'EOS': 10,
    'BCH': 0.1,
    'BSV': 1,
    'TRX': 1000,
}

exchange_name_list = []
open_order_list = []
next_open_price = []


direction_price_list = []
initial_account_list = []
grid_number_list = []
add_percentage_list = []
ceiling_percentage_list = []
price_precision_list = []
stop_profit_list = []
stop_loss_list = []
base_price_list = []
basic_price_list = []
trading_volume_list = []
max_amount_list = []

maker_close_number = []
is_begin = 0
def get_position(exchangesIndex):
    userPositio = {}

position = exchanges[exchangesIndex].GetPosition()
userPositio['buy_amount'] = 0
userPositio['buy_price_avg'] = 0
userPositio['buy_bond'] = 0
userPositio['buy_profit'] = 0
userPositio['buy_Margin'] = 0


userPositio['sell_amount'] = 0
userPositio['sell_price_avg'] = 0
userPositio['sell_profit'] = 0
userPositio['sell_bond'] = 0
userPositio['sell_Margin'] = 0

if position:
    if len(position) > 0:
        if exchange_name_list[exchangesIndex] == 'Futures_OKCoin':
        for index in range(len(position)):
            if position[index]['ContractType'] == contract_type:
            if position[index]['Type'] == 0:
            if contract_type == 'swap':
    userPositio['buy_amount'] = float(position[index]['Amount'])
userPositio['buy_price_avg'] = float(position[index]['Price'])
userPositio['buy_profit'] = float(position[index]['Info']['unrealized_pnl']) + float(position[index]['Info']['settled_pnl'])
userPositio['buy_Margin'] = float(position[index]['Margin'])
else :
    userPositio['buy_amount'] = float(position[index]['Amount'])
userPositio['buy_price_avg'] = float(position[index]['Price'])
userPositio['buy_profit'] = float(position[index]['Info']['long_pnl'])
userPositio['buy_Margin'] = float(position[index]['Margin'])
if position[index]['Type'] == 1:

    if contract_type == 'swap':
    userPositio['sell_amount'] = float(position[index]['Amount'])
userPositio['sell_price_avg'] = float(position[index]['Price'])
userPositio['sell_profit'] = float(position[index]['Info']['unrealized_pnl']) + float(position[index]['Info']['settled_pnl'])
userPositio['sell_Margin'] = float(position[index]['Margin'])
else :
    userPositio['sell_amount'] = float(position[index]['Amount'])
userPositio['sell_price_avg'] = float(position[index]['Price'])
userPositio['sell_profit'] = float(position[index]['Info']['short_pnl'])
userPositio['sell_Margin'] = float(position[index]['Margin'])
if exchange_name_list[exchangesIndex] == 'Futures_HuobiDM':
    for index in range(len(position)):
    if position[index]['ContractType'] == contract_type:
    if position[index]['Type'] == 0:
    userPositio['buy_amount'] = position[index]['Amount']
userPositio['buy_price_avg'] = position[index]['Price']
userPositio['buy_profit'] = position[index]['Info']['profit']
if position[index]['Type'] == 1:
    userPositio['sell_amount'] = position[index]['Amount']
userPositio['sell_price_avg'] = position[index]['Price']
userPositio['sell_profit'] = position[index]['Info']['profit']
if exchange_name_list[exchangesIndex] == 'Futures_Binance':
    if position[0]['Type'] == 0:
    userPositio['buy_amount'] = position[0]['Amount']
userPositio['buy_price_avg'] = position[0]['Price']
userPositio['buy_profit'] = position[0]['Profit']
if position[0]['Type'] == 1:
    userPositio['sell_amount'] = position[0]['Amount']
userPositio['sell_price_avg'] = position[0]['Price']
userPositio['sell_profit'] = position[0]['Profit']
if position == 0:
    userPositio['buy_amount'] = -1
userPositio['buy_price_avg'] = 0
userPositio['buy_bond'] = 0
userPositio['buy_profit'] = 0
userPositio['buy_Margin'] = 0


userPositio['sell_amount'] = -1
userPositio['sell_price_avg'] = 0
userPositio['sell_profit'] = 0
userPositio['sell_bond'] = 0
userPositio['sell_Margin'] = 0
if len(position) == 0:
    userPositio['buy_amount'] = 0
userPositio['buy_price_avg'] = 0
userPositio['buy_bond'] = 0
userPositio['buy_profit'] = 0
userPositio['buy_Margin'] = 0


userPositio['sell_amount'] = 0
userPositio['sell_price_avg'] = 0
userPositio['sell_profit'] = 0
userPositio['sell_bond'] = 0
userPositio['sell_Margin'] = 0
return userPositio

def cancel_order_for_index(exchangesIndex):
    exchanges[exchangesIndex].SetContractType(contract_type)
orders = _C(exchanges[exchangesIndex].GetOrders)
if len(orders) > 0:
    Log('存在未成交订单')
for z in range(len(orders)):
    exchanges[exchangesIndex].CancelOrder(orders[z]['Id'])

def get_Account(exchangesIndex):
    account_list = {}
account = _C(exchanges[exchangesIndex].GetAccount)
if exchange_name_list[exchangesIndex] == 'Futures_OKCoin':
    if contract_type == 'swap':
    account_list['account_rights'] = float(account['Info']['info']['equity'])
account_list['profit_real'] = float(account['Info']['info']['realized_pnl'])
account_list['risk_rate'] = float(account['Info']['info']['margin_ratio'])
else :
    account_list['account_rights'] = float(account['Info']['equity'])
account_list['profit_real'] = float(account['Info']['realized_pnl'])
account_list['risk_rate'] = float(account['Info']['margin_ratio'])


if exchange_name_list[exchangesIndex] == 'Futures_HuobiDM':
    for index in range(len(account['Info']['data'])):
    if account['Info']['data'][index]['symbol'] == operation_currency[exchangesIndex].upper():
    account_list['account_rights'] = account['Info']['data'][index]['margin_balance']
account_list['profit_real'] = account['Info']['data'][index]['profit_real']
account_list['risk_rate'] = account['Info']['data'][index]['risk_rate']


if exchange_name_list[exchangesIndex] == 'Futures_Binance':
    account_list['account_rights'] = account['Info']['assets'][0]['marginBalance']
account_list['profit_real'] = account['Info']['assets'][0]['marginBalance']
account_list['risk_rate'] = account['Info']['assets'][0]['marginBalance']

return account_list

# 初始资金
def update_initial_account():
    global base_account
for changesIndex in range(len(exchanges)):
    exchanges[changesIndex].SetContractType(contract_type)
account = get_Account(changesIndex)# Log(account)
base_account.append(account['account_rights'])

def statistical_orders(exchangesIndex):
    orders_data = {}
buy_open_list = []
buy_close_list = []

sell_open_list = []
sell_close_list = []

orders = _C(exchanges[exchangesIndex].GetOrders)
if len(orders) > 0:
    for orders_index in range(len(orders)):
    if orders[orders_index]['Type'] == 0 and orders[orders_index]['Offset'] == 0:
    buy_open_list.append(orders[orders_index]['Price'])

if orders[orders_index]['Type'] == 1 and orders[orders_index]['Offset'] == 0:
    sell_open_list.append(orders[orders_index]['Price'])

if orders[orders_index]['Type'] == 0 and orders[orders_index]['Offset'] == 1:
    sell_close_list.append(orders[orders_index]['Price'])

if orders[orders_index]['Type'] == 1 and orders[orders_index]['Offset'] == 1:
    buy_close_list.append(orders[orders_index]['Price'])

if len(buy_open_list) > 1:
    buy_open_list.sort(reverse = True)
if len(sell_open_list) > 1:
    sell_open_list.sort()

if len(buy_close_list) > 1:
    buy_close_list.sort()

if len(sell_close_list) > 1:
    sell_close_list.sort(reverse = True)

orders_data['buy_open_list'] = buy_open_list
orders_data['buy_close_list'] = buy_close_list
orders_data['sell_open_list'] = sell_open_list
orders_data['sell_close_list'] = sell_close_list

return orders_data

def cancel_order_for_price(exchangesIndex, peice_data):
    orders = _C(exchanges[exchangesIndex].GetOrders)
if len(orders) > 0:
    for orders_index in range(len(orders)):
    if orders[orders_index]['Price'] == peice_data:
    exchanges[exchangesIndex].CancelOrder(orders[orders_index]['Id'], '撤销价格为:' + str(orders[orders_index]['Price']) + '的订单')

def cancel_order_for_type(exchangesIndex, position_type):
    orders = _C(exchanges[exchangesIndex].GetOrders)
if len(orders) > 0:
    for orders_index in range(len(orders)):
    if orders[orders_index]['Type'] == position_type and orders[orders_index]['Offset'] == 0:
    exchanges[exchangesIndex].CancelOrder(orders[orders_index]['Id'], '撤销价格为:' + str(orders[orders_index]['Price']) + '的订单')

def start_string(exchangesIndex):

    return '账号:' + str(exchangesIndex) + '  ,'

def open_new_position(exchangesIndex, position_type, number):
    changesIndex = exchangesIndex
new_add_amount = number

if position_type == 1:
    if new_add_amount <= every_trade_amount:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('buy')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Buy(-1, new_add_amount)
if new_add_amount > every_trade_amount:
    newnew_add_amount = new_add_amount
while True:
    if newnew_add_amount >= every_trade_amount:
    exchanges[changesIndex].SetDirection('buy')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Buy(-1, float(every_trade_amount), start_string(changesIndex) + '总计下单:' + str(new_add_amount) + '张多单,剩余:' + str(newnew_add_amount))
newnew_add_amount = newnew_add_amount - every_trade_amount
Sleep(500)
if newnew_add_amount <= every_trade_amount and newnew_add_amount > 0:
    exchanges[changesIndex].SetDirection('buy')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Buy(-1, float(newnew_add_amount), start_string(changesIndex) + '总计下单:' + str(new_add_amount) + '张多单,剩余' + str(newnew_add_amount))
newnew_add_amount = 0
break

if position_type == 2:
    if new_add_amount <= every_trade_amount:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('sell')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Sell(-1, new_add_amount)
if new_add_amount > every_trade_amount:
    newnew_add_amount = new_add_amount
while True:
    if newnew_add_amount >= every_trade_amount:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('sell')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Sell(-1, every_trade_amount, start_string(changesIndex) + '总计下单' + str(new_add_amount) + '张空单,剩余' + str(newnew_add_amount))
Sleep(500)
newnew_add_amount = newnew_add_amount - every_trade_amount
if newnew_add_amount <= every_trade_amount and newnew_add_amount > 0:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('sell')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Sell(-1, newnew_add_amount, start_string(changesIndex) + '总计下单' + str(new_add_amount) + '张空单,剩余' + str(newnew_add_amount))
newnew_add_amount = 0
break

if position_type == 3:
    new_exchanges_position = get_position(changesIndex)
new_buy_amount = float(new_exchanges_position['buy_amount'])


if new_add_amount <= every_trade_amount:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('closebuy')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Sell(-1, new_add_amount)
if new_add_amount > every_trade_amount:
    newnew_add_amount = new_add_amount
if new_add_amount > new_buy_amount:
    newnew_add_amount = new_buy_amount
while True:
    if newnew_add_amount >= every_trade_amount:
    exchanges[changesIndex].SetDirection('closebuy')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Sell(-1, float(every_trade_amount), start_string(changesIndex) + '总计平仓' + str(new_add_amount) + '张多单,剩余' + str(newnew_add_amount))
newnew_add_amount = newnew_add_amount - every_trade_amount
if newnew_add_amount <= every_trade_amount and newnew_add_amount > 0:
    exchanges[changesIndex].SetDirection('closebuy')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Sell(-1, float(newnew_add_amount), start_string(changesIndex) + '总计平仓' + str(new_add_amount) + '张多单,剩余' + str(newnew_add_amount))
newnew_add_amount = 0
break

if position_type == 4:
    new_exchanges_position = get_position(changesIndex)
new_sell_amount = float(new_exchanges_position['sell_amount'])

if new_add_amount <= every_trade_amount:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('closesell')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Buy(-1, new_add_amount)
if new_add_amount > every_trade_amount:
    newnew_add_amount = new_add_amount
if new_add_amount > new_sell_amount:
    newnew_add_amount = new_sell_amount
while True:
    if newnew_add_amount >= every_trade_amount:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('closesell')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Buy(-1, every_trade_amount, start_string(changesIndex) + '总计平仓' + str(new_add_amount) + '张空单,剩余' + str(newnew_add_amount))

newnew_add_amount = newnew_add_amount - every_trade_amount
if newnew_add_amount <= every_trade_amount and newnew_add_amount > 0:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('closesell')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Buy(-1, newnew_add_amount, start_string(changesIndex) + '总计平仓' + str(new_add_amount) + '张空单,剩余' + str(newnew_add_amount))
newnew_add_amount = 0
break

def maker_new_position(exchangesIndex, position_type, trade_price, number):
    changesIndex = exchangesIndex
if len(open_order_list[changesIndex]) == 0:
    if position_type == 1:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('buy')
order_id = exchanges[changesIndex].Buy(trade_price, number)

updata_order_record(changesIndex, order_id)
updata_next_open_price(changesIndex, trade_price)
Log('存入订单号:' + str(order_id) + ',open_order_list[changesIndex]:' + str(open_order_list[changesIndex]))
if position_type == 2:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('sell')
order_id = exchanges[changesIndex].Sell(trade_price, number)
Log(str(order_id) + str(',') + str(trade_price) + str(',') + str(number))

updata_order_record(changesIndex, order_id)
updata_next_open_price(changesIndex, trade_price)

Log('存入订单号:' + str(order_id) + ',open_order_list[changesIndex]:' + str(open_order_list[changesIndex]))

if position_type == 3:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('closebuy')
exchanges[changesIndex].Sell(trade_price, number)
delete_open_order_list(changesIndex)
if position_type == 4:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('closesell')
exchanges[changesIndex].Buy(trade_price, number)
delete_open_order_list(changesIndex)

# 更新开仓订单
def updata_order_record(exchangesIndex, order_id):
    global open_order_list
if order_id:
    if len(order_id) > 7:
    new_open_order_list = []
new_open_order_list.append(order_id)

del open_order_list[exchangesIndex]
open_order_list.insert(exchangesIndex, new_open_order_list)

def delete_open_order_list(exchangesIndex):
    global open_order_list

Log(start_string(exchangesIndex) + ',开仓订单ID:' + str(open_order_list[exchangesIndex]) + '已被删除')
del open_order_list[exchangesIndex]
open_order_list.insert(exchangesIndex, [])


# 更新开仓价格
def updata_next_open_price(exchangesIndex, open_price):
    global next_open_price

del next_open_price[exchangesIndex]
next_open_price.insert(exchangesIndex, open_price)

# 基准价
def updata_base_price_list(exchangesIndex, price_data):
    global base_price_list

del base_price_list[exchangesIndex]
base_price_list.insert(exchangesIndex, price_data)

def add_maker_close_number(exchangesIndex):
    global maker_close_number

new_number = maker_close_number[exchangesIndex]
new_number = new_number + 1
del maker_close_number[exchangesIndex]
maker_close_number.insert(exchangesIndex, new_number)

# 监控开仓订单成交情况
def monitor_open_trade_status():
    for changesIndex in range(len(exchanges)):
    if len(open_order_list[changesIndex]) != 0:
    order = exchanges[changesIndex].GetOrder(open_order_list[changesIndex][0])

if order:
    if order['Status'] == 1:
    open_diff_price = float(float(base_price_list[changesIndex]) * float(add_percentage_list[changesIndex]))
if order['Type'] == 0:
    Log('价格为:' + str(order['Price']) + '的开多单已完全成交,触发平仓单')
maker_new_position(changesIndex, 3, order['Price'] + open_diff_price, order['Amount'])
add_maker_close_number(changesIndex)
if order['Type'] == 1:
    Log('价格为:' + str(order['Price']) + '的开空单已完全成交,触发平仓单')
maker_new_position(changesIndex, 4, order['Price'] - open_diff_price, order['Amount'])
add_maker_close_number(changesIndex)
break
if order['Status'] == 2:
    Log('订单已取消,删除订单号')
if order['DealAmount'] > 0:
    Log('订单已成交:' + str(order['DealAmount']) + '触发清仓')
if order['Type'] == 0:
    open_new_position(changesIndex, 3, order['DealAmount'])
if order['Type'] == 1:
    open_new_position(changesIndex, 4, order['DealAmount'])
delete_open_order_list(changesIndex)
break

def trade_direction(exchangesIndex, direction_type):
    global base_price_list
ticker = _C(exchanges[exchangesIndex].GetTicker)
new_price = ticker['Last']

new_exchanges_position = get_position(exchangesIndex)
new_buy_amount = float(new_exchanges_position['buy_amount'])
buy_price_avg = float(new_exchanges_position['buy_price_avg'])

new_sell_amount = float(new_exchanges_position['sell_amount'])
sell_price_avg = float(new_exchanges_position['sell_price_avg'])
all_orders = statistical_orders(exchangesIndex)
open_diff_price = float(float(base_price_list[exchangesIndex]) * float(add_percentage_list[exchangesIndex]))

min_price = basic_price_list[exchangesIndex] * (1 - grid_number_list[exchangesIndex] * add_percentage_list[exchangesIndex])
max_price = basic_price_list[exchangesIndex] * (1 + grid_number_list[exchangesIndex] * add_percentage_list[exchangesIndex])

if direction_type == 0:
    if new_buy_amount < max_amount_list[exchangesIndex]:
    if new_price > min_price:
    if len(all_orders['buy_open_list']) == 0 and len(all_orders['buy_close_list']) == 0:
    Log('---------------------------------------------------------------------------------------------------')
Log('没有开仓单和平仓单,初始化开仓')
maker_new_position(exchangesIndex, 1, float(base_price_list[exchangesIndex]) - open_diff_price, trading_volume_list[exchangesIndex])

if len(all_orders['buy_open_list']) == 0 and len(all_orders['buy_close_list']) > 0:
    Log('---------------------------------------------------------------------------------------------------')
Log('有平仓单,没有开仓单')
maker_new_position(exchangesIndex, 1, all_orders['buy_close_list'][0] - open_diff_price * 2, trading_volume_list[exchangesIndex])

# 更新基准价
if len(all_orders['buy_open_list']) == 1 and len(all_orders['buy_close_list']) == 0:
    open_diff_price = float(float(base_price_list[exchangesIndex]) * float(add_percentage_list[exchangesIndex]))
if base_price_list[exchangesIndex] + open_diff_price <= new_price:
    if basic_price_list[exchangesIndex] * (1 + ceiling_percentage_list[exchangesIndex]) >= new_price:
    Log('---------------------------------------------------------------------------------------------------')
Log('基准价:' + str(base_price_list[exchangesIndex]) + ',当前价:' + str(new_price) + ',触发更新基准价到:' + str(base_price_list[exchangesIndex] + open_diff_price))
cancel_order_for_type(exchangesIndex, 0)
updata_base_price_list(exchangesIndex, base_price_list[exchangesIndex] + open_diff_price)

if float(base_price_list[exchangesIndex]) - float(all_orders['buy_open_list'][0]) > 1.5 * open_diff_price:
    Log('---------------------------------------------------------------------------------------------------')
cancel_order_for_price(exchangesIndex, all_orders['buy_open_list'][0])
maker_new_position(exchangesIndex, 1, base_price_list[exchangesIndex] - open_diff_price, trading_volume_list[exchangesIndex])
Log('没有平仓单,开仓价离基准价过远,重新下单')

# 补单
if len(all_orders['buy_open_list']) > 0 and len(all_orders['buy_close_list']) > 0:
    open_diff_price = float(float(base_price_list[exchangesIndex]) * float(add_percentage_list[exchangesIndex]))
if float(all_orders['buy_close_list'][0]) - float(all_orders['buy_open_list'][0]) >= 2.9 * float(open_diff_price):
    Log('---------------------------------------------------------------------------------------------------')
maker_new_position(exchangesIndex, 1, all_orders['buy_open_list'][0] + open_diff_price, trading_volume_list[exchangesIndex])
cancel_order_for_price(exchangesIndex, all_orders['buy_open_list'][0])
Log('开多价:' + str(all_orders['buy_open_list'][0]) + ',平多价:' + str(all_orders['buy_close_list'][0]) + ',触发补多单,价格为:' + str(all_orders['buy_open_list'][0] + open_diff_price))

if direction_type == 1:
    if new_sell_amount < max_amount_list[exchangesIndex]:
    if new_price < max_price:
    if len(all_orders['sell_open_list']) == 0 and len(all_orders['sell_close_list']) == 0:
    Log('---------------------------------------------------------------------------------------------------')
Log('没有开空单和平空单,初始化开仓')
open_diff_price = float(float(base_price_list[exchangesIndex]) * float(add_percentage_list[exchangesIndex]))
maker_new_position(exchangesIndex, 2, base_price_list[exchangesIndex] + open_diff_price, float(trading_volume_list[exchangesIndex]))

# 有卖单, 根据卖单开仓
if len(all_orders['sell_open_list']) == 0 and len(all_orders['sell_close_list']) > 0:
    Log('---------------------------------------------------------------------------------------------------')
Log('有平空单,没有开多单')
open_diff_price = float(float(base_price_list[exchangesIndex]) * float(add_percentage_list[exchangesIndex]))
maker_new_position(exchangesIndex, 2, all_orders['sell_close_list'][0] + open_diff_price * 2, trading_volume_list[exchangesIndex])

# 更新基准价
if len(all_orders['sell_open_list']) == 1 and len(all_orders['sell_close_list']) == 0:
    open_diff_price = float(float(base_price_list[exchangesIndex]) * float(add_percentage_list[exchangesIndex]))

if base_price_list[exchangesIndex] - open_diff_price >= new_price:
    if basic_price_list[exchangesIndex] * (1 - ceiling_percentage_list[exchangesIndex]) <= new_price:
    Log('---------------------------------------------------------------------------------------------------')
Log('基准价:' + str(base_price_list[exchangesIndex]) + ',当前价:' + str(new_price) + ',触发更新基准价到:' + str(base_price_list[exchangesIndex] - open_diff_price))
cancel_order_for_type(exchangesIndex, 1)
updata_base_price_list(exchangesIndex, base_price_list[exchangesIndex] - open_diff_price)

if float(all_orders['sell_open_list'][0]) - float(base_price_list[exchangesIndex]) > 1.5 * open_diff_price:
    Log('---------------------------------------------------------------------------------------------------')
Log('没有平仓单,开仓价离基准价过远,重新下单,差价:' + str(float(all_orders['sell_open_list'][0]) - float(base_price_list[exchangesIndex])) + ',开仓差价:' + str(open_diff_price))
cancel_order_for_price(exchangesIndex, all_orders['sell_open_list'][0])
maker_new_position(exchangesIndex, 2, base_price_list[exchangesIndex] + open_diff_price, trading_volume_list[exchangesIndex])

# 补单
if len(all_orders['sell_open_list']) > 0 and len(all_orders['sell_close_list']) > 0:

    open_diff_price = float(float(base_price_list[exchangesIndex]) * float(add_percentage_list[exchangesIndex]))
if float(all_orders['sell_open_list'][0]) - float(all_orders['sell_close_list'][0]) >= 2.9 * float(open_diff_price):
    Log('---------------------------------------------------------------------------------------------------')
maker_new_position(exchangesIndex, 2, all_orders['sell_open_list'][0] - open_diff_price, trading_volume_list[exchangesIndex])
cancel_order_for_price(exchangesIndex, all_orders['sell_open_list'][0])
Log('开空价:' + str(all_orders['sell_open_list'][0]) + ',平空价:' + str(all_orders['sell_close_list'][0]) + ',触发补空单,价格为:' + str(all_orders['sell_open_list'][0] - open_diff_price))

def begin():
    for changesIndex in range(len(exchanges)):
    if is_begin == 0:
    if direction == 0:
    trade_direction(changesIndex, 0)
if direction == 1:
    trade_direction(changesIndex, 1)

def update_table(): #基础信息
position_table_rows = []
account_table_rows = []
account_table_rowssss = []
for changesIndex in range(len(exchanges)):
    exchanges[changesIndex].SetContractType(contract_type)
account = get_Account(changesIndex)
account_rights = account['account_rights']
profit_real = account['profit_real']
risk_rate = account['risk_rate']

new_position = get_position(changesIndex)
buy_amount = float(new_position['buy_amount'])
buy_profit = float(new_position['buy_profit'])
buy_price_avg = float(new_position['buy_price_avg'])
sell_amount = float(new_position['sell_amount'])
sell_profit = float(new_position['sell_profit'])
sell_price_avg = float(new_position['sell_price_avg'])

min_price = 0
max_price = 0

all_orders = statistical_orders(changesIndex)
new_open_order_list = []
new_close_order_list = []

if direction == 0:
    min_price = base_price_list[changesIndex] * (1 - grid_number_list[changesIndex] * add_percentage_list[changesIndex])
max_price = basic_price_list[changesIndex] * (1 + ceiling_percentage_list[changesIndex])

new_open_order_list = all_orders['buy_open_list']
new_close_order_list = all_orders['buy_close_list']

if direction == 1:
    min_price = base_price_list[changesIndex] * (1 + grid_number_list[changesIndex] * add_percentage_list[changesIndex])
max_price = basic_price_list[changesIndex] * (1 - ceiling_percentage_list[changesIndex])

new_open_order_list = all_orders['sell_open_list']
new_close_order_list = all_orders['sell_close_list']

ticker = _C(exchanges[changesIndex].GetTicker)
new_price = ticker['Last']

open_new_number = 0
DealAmount_number = 0
if len(open_order_list[changesIndex]) > 0:
    order = exchanges[changesIndex].GetOrder(open_order_list[changesIndex][0])
open_new_number = order['Amount']
DealAmount_number = order['DealAmount']

open_diff_price = float(float(base_price_list[changesIndex]) * float(add_percentage_list[changesIndex]))

position_rows = [str(changesIndex), str(initial_account_list[changesIndex]), str(account_rights), str(base_price_list[changesIndex]), str(open_diff_price), str(buy_amount), str(buy_profit), str(buy_price_avg), str(sell_amount), str(sell_profit), str(sell_price_avg), str(open_new_number), str(DealAmount_number)]
position_table_rows.append(position_rows)

position_rowsss = [str(changesIndex), str(grid_number_list[changesIndex]), str(base_price_list[changesIndex]), str(min_price), str(max_price), str(new_open_order_list), str(new_close_order_list), str(open_order_list[changesIndex]), str(new_price), str(len(new_close_order_list))]
account_table_rowssss.append(position_rowsss)


direction_string = '多'
if direction == 1:
    direction_string = '空'

account_rows = [str(base_account[changesIndex]), str(account_rights), str(profit_real), str(direction_string), str(maker_close_number[changesIndex])]
account_table_rows.append(account_rows)




position_table = {
    "type": 'table',
    "title": '持仓信息',
    "cols": ['ID', '初始资产', '当前资产', '基准价', '加仓差价', '多仓持仓量', '多仓亏盈', '多仓持仓均价', '空仓持仓量', '空仓亏盈', '空仓持仓均价', '挂单量', '已成交量'],
    "rows": position_table_rows
}


position_tablee = {
    "type": 'table',
    "title": '参数信息',
    "cols": ['ID', '网格数量', '初始价格', '加仓,价格下限', '基准价更新,上限', '开仓挂单价格', '平仓挂单订单簿', '开仓订单ID', '当前价', '未平仓次数'],
    "rows": account_table_rowssss
}



account_table = {
    "type": 'table',
    "title": '账户信息',
    "cols": ['初始账户权益', '当前账户权益', '当前已实现亏盈', '方向', '挂卖单次数'],
    "rows": account_table_rows
}
LogStatus('`' + json.dumps([position_table, position_tablee, account_table]) + '`' + '\n' + '【当前价格:】' + str(new_price) + '\n')

def get_command_data():
    cmd = GetCommand()
if cmd:
    Log(cmd)
Log(type(cmd))
if type(cmd) == str:
    newString = cmd[13: ]
command_list = newString.split('_')
if len(command_list) == 2:
    if command_list[0] == 'closebuy':
    for changesIndex in range(len(exchanges)):
    Log('平多,平仓量:' + str(command_list[1]))
new_exchanges_position = get_position(changesIndex)
new_buy_amount = float(new_exchanges_position['buy_amount'])
buy_price_avg = float(new_exchanges_position['buy_price_avg'])

new_sell_amount = float(new_exchanges_position['sell_amount'])
sell_price_avg = float(new_exchanges_position['sell_price_avg'])
if new_buy_amount > 0:
    new_add_amount = float(command_list[1])
if new_add_amount <= every_trade_amount:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('closebuy')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Sell(-1, new_add_amount)
if new_add_amount > every_trade_amount:
    newnew_add_amount = new_add_amount
while True:

    if newnew_add_amount >= every_trade_amount:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('closebuy')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Sell(-1, every_trade_amount)

newnew_add_amount = newnew_add_amount - every_trade_amount
if newnew_add_amount <= every_trade_amount and newnew_add_amount > 0:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('closebuy')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Sell(-1, every_trade_amount)
newnew_add_amount = 0
break

elif command_list[0] == 'closesell':
    Log('平空,平仓量:' + str(command_list[1]))
for changesIndex in range(len(exchanges)):
    new_exchanges_position = get_position(changesIndex)
new_buy_amount = float(new_exchanges_position['buy_amount'])
buy_price_avg = float(new_exchanges_position['buy_price_avg'])

new_sell_amount = float(new_exchanges_position['sell_amount'])
sell_price_avg = float(new_exchanges_position['sell_price_avg'])

if new_sell_amount > 0:
    new_add_amount = float(command_list[1])
if new_add_amount <= every_trade_amount:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('closesell')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Buy(-1, new_add_amount)
if new_add_amount > every_trade_amount:
    newnew_add_amount = new_add_amount
while True:

    if newnew_add_amount >= every_trade_amount:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('closesell')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Buy(-1, every_trade_amount)

newnew_add_amount = newnew_add_amount - every_trade_amount
if newnew_add_amount <= every_trade_amount and newnew_add_amount > 0:
    exchanges[changesIndex].SetContractType(contract_type)
exchanges[changesIndex].SetDirection('closesell')# exchanges[changesIndex].SetMarginLevel(margin_level)
exchanges[changesIndex].Buy(-1, every_trade_amount)
newnew_add_amount = 0
break

def Cancel_all_Order():
    for changesIndex in range(len(exchanges)):
    orders = _C(exchanges[changesIndex].GetOrders)
if len(orders) > 0:
    for orders_index in range(len(orders)):
    exchanges[changesIndex].CancelOrder(orders[orders_index]['Id'], '撤销价格为:' + str(orders[orders_index]['Price']) + '的订单')

def initialize_data():
    global direction_price_list, initial_account_list, grid_number_list, add_percentage_list, ceiling_percentage_list, max_amount_list, price_precision_list, stop_profit_list, stop_loss_list, base_price_list, basic_price_list, trading_volume_list


direction_price_new = direction_price.split(',')
initial_account_new = initial_account.split(',')
grid_number_new = grid_number.split(',')
add_percentage_new = add_percentage.split(',')
ceiling_percentage_new = ceiling_percentage.split(',')
price_precision_new = price_precision.split(',')# stop_profit_new = stop_profit.split(',')# stop_loss_new = stop_loss.split(',')
base_price_new = base_price.split(',')
trading_volume_new = trading_volume.split(',')
max_amount_new = max_amount.split(',')


direction_price_list = [float(i) for i in direction_price_new]
initial_account_list = [float(i) for i in initial_account_new]
grid_number_list = [float(i) for i in grid_number_new]
add_percentage_list = [float(i) for i in add_percentage_new]
ceiling_percentage_list = [float(i) for i in ceiling_percentage_new]
price_precision_list = [float(i) for i in price_precision_new]# stop_profit_list = [float(i) for i in stop_profit_new]# stop_loss_list = [float(i) for i in stop_loss_new]
base_price_list = [float(i) for i in base_price_new]
basic_price_list = [float(i) for i in base_price_new]
trading_volume_list = [float(i) for i in trading_volume_new]
max_amount_list = [float(i) for i in max_amount_new]

def cancel_all_position():
    for changesIndex in range(len(exchanges)):
    while True:
    Log('进入清仓循环')
Sleep(500)
Cancel_all_Order()
exchanges[changesIndex].SetContractType(contract_type)
exchanges_position = get_position(changesIndex)

new_buy_amount = float(exchanges_position['buy_amount'])
new_sell_amount = float(exchanges_position['sell_amount'])

if new_sell_amount > 0:
    open_new_position(changesIndex, 4, new_sell_amount)
if new_buy_amount > 0:
    Log(new_buy_amount)
open_new_position(changesIndex, 3, new_buy_amount)
if new_sell_amount == 0 and new_buy_amount == 0:
    Log('退出清仓循环')
break

def dynamic_grid():
    for changesIndex in range(len(exchanges)):
    ticker = _C(exchanges[changesIndex].GetTicker)
new_price = ticker['Last']

new_exchanges_position = get_position(changesIndex)
new_buy_amount = float(new_exchanges_position['buy_amount'])
buy_price_avg = float(new_exchanges_position['buy_price_avg'])

new_sell_amount = float(new_exchanges_position['sell_amount'])
sell_price_avg = float(new_exchanges_position['sell_price_avg'])
all_orders = statistical_orders(changesIndex)
if direction == 0:
    if new_buy_amount >= max_amount_list[changesIndex]:
    Log(start_string(changesIndex) + '当前持仓:' + str(new_buy_amount) + '最大持仓:' + str(max_amount_list[changesIndex]) + '触发斩仓')
cancel_order_for_price(changesIndex, all_orders['buy_close_list'][-1])
open_new_position(changesIndex, 3, trading_volume_list[changesIndex])


if direction == 1: #Log('当前持仓' + str(new_sell_amount) + ',最大持仓' + str(max_amount_list[changesIndex]))

if new_sell_amount >= max_amount_list[changesIndex]:
    Log('当前持仓' + str(new_sell_amount) + ',最大持仓' + str(max_amount_list[changesIndex]))
Log(start_string(changesIndex) + '当前持仓:' + str(new_sell_amount) + '最大持仓:' + str(max_amount_list[changesIndex]) + '触发斩仓')
cancel_order_for_price(changesIndex, all_orders['sell_close_list'][-1])
open_new_position(changesIndex, 4, trading_volume_list[changesIndex])

def close_all_position():
    global is_begin
for changesIndex in range(len(exchanges)):
    exchangesIndex = changesIndex
ticker = _C(exchanges[exchangesIndex].GetTicker)
new_price = ticker['Last']

new_exchanges_position = get_position(exchangesIndex)
new_buy_amount = float(new_exchanges_position['buy_amount'])
buy_price_avg = float(new_exchanges_position['buy_price_avg'])

new_sell_amount = float(new_exchanges_position['sell_amount'])
sell_price_avg = float(new_exchanges_position['sell_price_avg'])
all_orders = statistical_orders(exchangesIndex)
open_diff_price = float(float(base_price_list[exchangesIndex]) * float(add_percentage_list[exchangesIndex]))

min_price = basic_price_list[exchangesIndex] * (1 - grid_number_list[exchangesIndex] * add_percentage_list[exchangesIndex])
max_price = basic_price_list[exchangesIndex] * (1 + grid_number_list[exchangesIndex] * add_percentage_list[exchangesIndex])

if direction == 0:
    if new_buy_amount >= max_amount_list[exchangesIndex]:
    Cancel_all_Order()
cancel_all_position()
is_begin = 1
if direction == 1:
    if new_sell_amount >= max_amount_list[exchangesIndex]:
    Cancel_all_Order()
cancel_all_position()
is_begin = 1

def main():
    global operation_currency, contract_type, exchange_name_list, open_order_list, next_open_price, maker_close_number
SetErrorFilter("502:|503:|429:|429|500:|500|400:|400")
if futures_type == 1:
    contract_type = 'swap'

initialize_data()
for changesIndex in range(len(exchanges)):
    exchanges[changesIndex].SetContractType(contract_type)
open_order_list.append([])
next_open_price.append(0)
maker_close_number.append(0)

exchange_name = exchanges[changesIndex].GetName()
name_string_bytes = exchange_name
if type(exchange_name) == bytes:
    name_string_bytes = exchange_name.decode()
exchange_name_list.append(name_string_bytes)

exchanges[changesIndex].SetPrecision(price_precision_list[changesIndex], 1)
exchanges[changesIndex].SetMarginLevel(margin_level)
currency_bytes = exchanges[changesIndex].GetCurrency()
currency_string_bytes = currency_bytes
if type(currency_bytes) == bytes:
    currency_string_bytes = currency_bytes.decode()
currency_list = currency_string_bytes.split('_')
operation_currency.append(currency_list[0])

if direction == 0:
    cancel_order_for_type(changesIndex, 0)
cancel_order_for_type(changesIndex, 1)
if direction == 1:
    cancel_order_for_type(changesIndex, 0)
cancel_order_for_type(changesIndex, 1)

update_initial_account()




if is_cancel_position:
    Cancel_all_Order()
cancel_all_position()
while True:
    try:
    if is_close:
    close_all_position()
if is_dynamic_grid:
    dynamic_grid()
monitor_open_trade_status()
Sleep(1000 * 10)
begin()
update_table()
get_command_data()
Sleep(20000)
except:
    Sleep(2000)

More