I have a universe of stocks that are not so liquid, but I am executing trades every 30 mins.
Before I execute each trade, I will make sure I have cancelled all the open orders, using:
open_orders = get_open_orders()
cancel_order(order for order in open_orders)
However, whenever I check the open_orders after the above code is executed, there are still orders that are not cancelled.
Actually I did this:
open_orders = get_open_orders()
N1=len(open_orders)
cancel_order(order for order in open_orders)
open_orders = get_open_orders()
N2=len(open_orders)
Strangely, N1=N2 all the time. It is not supposed to be this way.
Please help.
*CODE:*
import numpy as np
import pandas as pd
def initialize(context):
#initiate symbols we want to trade.
#should read from master.csv file when available.
#below are only randomly picked stocks from asian ETF markets
context.stocks=symbols('EWT',
'EWY',
'AAXJ',
'VPL',
'EEP',
'EWA',
'GMF',
'EWS',
'IPAC',
'FHK',
#'HAUD',
'DBKO',
'ENZL',
'AXJL',
'FPA')
'''
context.stocks=symbols('APB','APF','CAF','CHN','GCH','GRR','IAE','IF','IFN','IIF','JEQ','JFC','JOF','KEF','KF','SGF','TDF','TTF','TWN')
'''
context.weights=pd.Series([0.33,0.34,0.33])
context.longNum=3
context.shortNum=3
context.tradeFreq=30 #only make a trade every 60 minutes
#define the trading time as how many minutes after market open
context.tradingTime=range(1,400,context.tradeFreq)
set_commission(commission.PerShare(cost=0.02, min_trade_cost=0.1))
set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025,price_impact=0.1))
'''
for minute in context.tradingTime:
schedule_function(func=executeTrade,
date_rule=date_rules.every_day(),
time_rule=time_rules.market_open(minutes=minute))
'''
def handle_data(context, data):
mins = get_datetime().minute
#print mins
if mins in context.tradingTime:
context.yesterdayClosePrices=history(2,'1d','price').iloc[0]
context.currentPrices=history(1,'1m','price').iloc[0]
sortedStocks=sort_returns(context)
nstocks=len(sortedStocks)
if nstocks<(context.longNum+context.shortNum):
longNum=nstocks/2
shortNum=nstocks/2
weight=1.0/longNum
for i in xrange(1,longNum):
weights=pd.Series()
weights.set_value(i,weight)
else:
longNum=context.longNum
shortNum=context.shortNum
weights=context.weights
longStocks=sortedStocks[:longNum]
shortStocks=sortedStocks[-shortNum:]
#Cancel any orders that are still open
open_orders = get_open_orders()
cancel_order(order for order in open_orders)
#start trading
longCounter=0
shortCounter=0
for stock in context.stocks:
if stock in longStocks:
order_target_percent(stock,weights[longCounter])
longCounter=longCounter+1
elif stock in shortStocks:
order_target_percent(stock,-weights[shortCounter])
shortCounter=shortCounter+1
else:
order_target_percent(stock,0.0)
record(total_position_value=context.account.total_positions_value)
log.info("longs: "+", ".join([long_.symbol for long_ in longStocks]))
log.info("shorts: " +", ".join([short_.symbol for short_ in shortStocks]))
def sort_returns(context):
#rank stock returns by the ascending order
stockReturns=pd.DataFrame(
context.currentPrices/context.yesterdayClosePrices-1,
index=context.currentPrices.index)
stockReturns.columns=['Returns']
stockReturns=stockReturns.dropna(how='any')
ranks=(stockReturns.sort(['Returns'])).index
#ranks=context.stocks
return ranks