from alice_blue import *
import pdb
import datetime
import time
import pandas as pd
access_token = '1JekMg.ezoSy4HW8rn3zjUzpRWR2fA2P9c6yQLjGWHdnCvXtOs'
alice = AliceBlue(username='', password='', access_token= '5ENG1JekMg.ezoSy4HW8rn3zjUzpRWR2fA2P9c6yQLjGWHdnCvXtOs', master_contracts_to_download=['NSE', 'NFO'])
traded_stocks = []
socket_opened = False
def event_handler_quote_update(message):
print(f"quote update {message}")
name = message['instrument'].symbol
openx = message['open']
high = message['high']
low = message['low']
close = message['close']
ltp = message['ltp']
cap = 100000
curr_time=datetime.datetime.now()
crt_time=curr_time.time()
breakout=datetime.time(18, 30)
if (crt_time >= breakout) and (name not in traded_stocks) and (ltp >= high):
print(f"buy: {name} , ltp: {ltp}")
traded_stocks.append(name)
message = alice.place_order(transaction_type = TransactionType.Buy, instrument = alice.get_instrument_by_symbol('NSE', name), quantity = 1 , order_type = OrderType.Limit, product_type = ProductType.BracketOrder, price = high, trigger_price = None, stop_loss =low, square_off =float(format((high-low), ".1f")), trailing_sl = None, is_amo = False)
sleep(10)
else :
print(f"time not satisfied is {curr_time}")
def open_callback():
global socket_opened
socket_opened = True
alice.start_websocket(subscribe_callback=event_handler_quote_update,
socket_open_callback=open_callback,
run_in_background=True)
while(socket_opened==False):
pass
instrument = [alice.get_instrument_by_symbol('NSE', 'ICICIBANK')]
while True:
alice.subscribe(instrument, LiveFeedType.MARKET_DATA)
Im trying to code a Open Range Breakout Strategy with this alice(https://pypi.org/project/alice-blue/)
But i cant breakthrough what concept to use
Can anyone Suggest a CODE based on provided link to alice-blue data and code please
I tried of placing order on specific time alone but the code runs and fires orders continously
Want a Suggestion with Function and the Order must be placed only once for a certain script
Step 1: Create a cron job at 9:30 AM and Store the Highest Price in DB.
Step 2: Create another cron job for every 15 mins --> Compare LTP > High
Step 3: If the condition is true --> Place an order and store the order ID & instrument
Step 4: Create one more cron job for exit signal --> compare with Target or SL price ---> Place Exit Order
Related
First one:
### configuration details
TELEGRAM_TOKEN = '' # telegram bot token
TELEGRAM_CHANNEL ='' # channel id
INTERVAL = '1m' # binance time interval
SHORT_EMA = 7 # short interval for ema
LONG_EMA = 21 # long interval for ema
Here is my second code:
import requests
import talib
import time
import numpy as np
import websocket
from config import TELEGRAM_TOKEN, TELEGRAM_CHANNEL , INTERVAL, SHORT_EMA , LONG_EMA
def streamKline(currency, interval):
websocket.enableTrace(False)
socket = f'wss://stream.binance.com:9443/ws/{currency}#kline_{interval}'
ws = websocket.WebSocketApp(socket)
ws.run_forever()
#SYMBOLS TO LOOK FOR ALERTS
SYMBOLS = [
"ETHUSDT",
"BTCUSDT",
"ATOMUSDT",
"BNBUSDT",
"FTMBUSD",
"ENJUSDT",
"WAXPUSDT"
]
#sending alerts to telegram
def send_message(message):
url = "https://api.telegram.org/bot{}/sendMessage?chat_id={}&text={}&parse_mode=markdown".format(TELEGRAM_TOKEN,TELEGRAM_CHANNEL,message)
res = requests.get(url);print(url);
return res
# getting klines data to process
def streamKline(symbol):
data = socket.streamKline(symbol=symbol,interval=INTERVAL,limit=300) # more data means more precision but at the trade off between speed and time
return_data = []
# taking closing data for each kline
for each in data:
return_data.append(float(each[4])) # 4 is the index of the closing data in each kline
return np.array(return_data) # returning as numpy array for better precision and performance
def main():
# making a infinite loop that keeps checking for condition
while True:
#looping through each coin
for each in SYMBOLS:
data = streamKline(each)
ema_short = talib.EMA(data,int(SHORT_EMA))
ema_long = talib.EMA(data,int(LONG_EMA))
last_ema_short = ema_short[-2]
last_ema_long = ema_long[-2]
ema_short = ema_short[-1]
ema_long = ema_long[-1]
# conditions for alerts
if(ema_short > ema_long and last_ema_short < last_ema_long):
message = each + "bullcoming "+ str(SHORT_EMA) + " over "+str(LONG_EMA);print(each ,"alert came");
send_message(message);
time.sleep(0.5);
# calling the function
if __name__ == "__main__":
main()
The part of config is all settle done, just second for the kline data, the error mention lot like this.
data = socket.streamKline(symbol=symbol,interval=INTERVAL,limit=300) # more data means more precision but at the
trade off between speed and time
NameError: name 'socket' is not defined
I just don't know how to do it, I want build a ema alert that can give me a message when I am not watching chart, through this way seems not work, I have tried many times, and also find many video but still, I am just an beginner, nothing improving at all.
I'm having some problems using the ATR-Indicator in the TA-Lib library. Every other indicator seems to work just fine.
Here's the code in python:
import json
import numpy
import talib
import websocket
# *******PARAMETERS
# Name of Socket for BTC in USDT 1min Candle
SOCKET = "wss://stream.binance.com:9443/ws/btcusdt#kline_1m"
# Arrays
closes = []
highs = []
lows = []
# ***Websocket definition***
def on_open_ws(ws):
print('opened connection')
def on_close_ws(ws):
print('closed connection')
def on_message_ws(ws, message):
json_message = json.loads(message)
# only watching the candle infos in received message
candle = json_message['k']
# getting close, high and low values
is_candle_closed = candle['x']
close = float(candle['c'])
high = float(candle['h'])
low = float(candle['l'])
if is_candle_closed:
closes.append(close) # add close price to closes-array
np_closes = numpy.array(closes) # convert closes-array in numpy
c_close = np_closes[-1] # current close
p_close = np_closes[-2] # previous close
print(len(closes))
highs.append(high)
np_highs = numpy.array(highs)
last_high = np_highs[-1]
lows.append(low)
np_lows = numpy.array(lows)
last_low = np_lows[-1]
# Set ATR
atr = talib.ATR(np_highs, np_lows, np_closes, timeperiod=14)
last_atr = atr[-1]
print('last atr')
print(last_atr)
ws = websocket.WebSocketApp(SOCKET, on_open=on_open_ws, on_close=on_close_ws, on_message=on_message_ws)
# Run websocket app
ws.run_forever()
The last commands "print('last atr') and print(last_atr) do not print, suggesting that the atr isnt working.
Does somehow have any idea what could be the problem?
I tried using just the last values of high, low and close as well as the non-numpied values, but this doesn't change anything. I'm not even getting the "nan" answer for the first few values...
Your first call of on_message_ws() with is_candle_closed == true crashes at line p_close = np_closes[-2] # previous close as there is only 1 element in closes yet.
After this crash the next call of on_message_ws() with is_candle_closed == true will continue with len(closes) == 2 and len(lows) == len(highs) == 1 and then crash at talib.ATR() with Exception: input array lengths are different.
And so on.
P.S. I would also suggest to use numpy.array(closes, dtype='double') instead of numpy.array(closes) as talib.ATR() is able to crash with Exception: input array type is not double. That's not happening with current data received from binance, but just to be safe I would ensure the arrays are converted to double.
So i solved my problem by coding my own ATR, which was a much easier solution then i thought. If it can help anyone heres the code
def true_range(high, low, p_close):
high_low = high - low
high_close = numpy.abs(high - p_close)
low_close = numpy.abs(low - p_close)
trange = max(high_low, high_close, low_close)
return trange
# Set TR
last_tr = true_range(last_high, last_low, p_close)
tr.append(last_tr)
if len(tr) > ATR_PERIOD:
del tr[0]
# Set ATR (SMA smoothing but need RMA)
atr = sum(tr) / ATR_PERIOD
print('atr ', atr)
ATR_PERIOD is the period you want to set.
For the length of ATR_PERIOD you will obviously get wrong numbers, but afterwards you should be fine
I'm new to Python (programming in general) and I've been trying to learn myself through youtube and sites like stackoverflow. In the meantime I've programmed a working trading bot in binance. But now I'm working on a tweak in this bot on the sell part, which I cannot get working. Trying the parameters standalone does work, but when I combine the two it does not work. I'm doing something wrong, but can't figure out what it is. (It still does buy, but does not sell.)
In the code, on the SELL part, everything works just fine when I change TRADE_QUANTITY_SELL for TRADE_QUANTITY_BUY (so it uses the same value on both buy and sell order).
The sell part does work, when I try this standalone:
balance = client.get_asset_balance(asset='BTC')
FREEBTC = float(balance['free'])
TRADE_QUANTITY_SELL = round(FREEBTC, 5)
#print (TRADE_QUANTITY_SELL)
order = client.create_test_order(
symbol=TRADE_SYMBOL,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=TRADE_QUANTITY_SELL)
print(order)
This is the complete bot version I've tried last. It still does buy, but does not sell.
import websocket, json, pprint, talib, numpy
import config
from binance.client import Client
from binance.enums import *
SOCKET = "wss://stream.binance.com:9443/ws/btceur#kline_5m"
RSI_PERIOD = 14
RSI_OVERBOUGHT = 70
RSI_OVERSOLD = 30
TRADE_SYMBOL = 'BTCEUR'
TRADE_QUANTITY_BUY = 0.002
closes = []
client = Client(config.API_KEY, config.API_SECRET)
balance = client.get_asset_balance(asset='BTC')
FREEBTC = float(balance['free'])
TRADE_QUANTITY_SELL = round(FREEBTC, 6)
#print(SELL_TOTAL)
def order(side, quantity, symbol, order_type=ORDER_TYPE_MARKET):
try:
print("sending order")
order = client.create_order(symbol=symbol, side=side, type=order_type, quantity=quantity)
print(order)
except Exception as e:
print("an exception occured - {}".format(e))
return False
return True
def on_open(ws):
print('opened connection')
def on_close(ws):
print('closed connection')
def on_message(ws, message):
global closes
print('received message')
json_message = json.loads(message)
pprint.pprint(json_message)
candle = json_message['k']
is_candle_closed = candle['x']
close = candle['c']
in_position = False
#also tried to put the TRADE_QUANTITY_SELL params here, also does not work
if is_candle_closed:
print("candle closed at {}".format(close))
closes.append(float(close))
print("closes")
print(closes)
if len(closes) > RSI_PERIOD:
np_closes = numpy.array(closes)
rsi = talib.RSI(np_closes, RSI_PERIOD)
print("all rsis calculated so far")
print(rsi)
last_rsi = rsi[-1]
print("the current rsi is {}".format(last_rsi))
if last_rsi > RSI_OVERBOUGHT:
if in_position:
print("Overbought! Sell! Sell! Sell!")
#put binance order logic here
order_succeeded = order(SIDE_SELL, TRADE_QUANTITY_SELL, TRADE_SYMBOL)
if order_succeeded:
in_position = False
else:
print("It is overbought, but we don't own any. Nothing to do.")
if last_rsi < RSI_OVERSOLD:
if in_position:
print("Oversold! Buy! Buy! Buy!")
#print("It is oversold, but you already own it, nothing to do")
order_succeeded = order(SIDE_BUY, TRADE_QUANTITY_BUY, TRADE_SYMBOL)
if order_succeeded:
in_position = True
else:
print("Oversold! Buy! Buy! Buy!")
#put binance order logic here
order_succeeded = order(SIDE_BUY, TRADE_QUANTITY_BUY, TRADE_SYMBOL)
if order_succeeded:
in_position = True
ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message)
ws.run_forever( )
I'm not sure if this part
if last_rsi > RSI_OVERBOUGHT:
if in_position:
will ever be in_position eq True
in_position = False is create localy and when on_message ends it is still there in python(in some languages may not) but... next time on_message is called it will be overriten to False
Am I right?
move in_position = False to the top and see if it works
In the part that works...
balance = client.get_asset_balance(asset='BTC')
FREEBTC = float(balance['free'])
TRADE_QUANTITY_SELL = round(FREEBTC, 5)
#print (TRADE_QUANTITY_SELL)
order = client.create_test_order(
symbol=TRADE_SYMBOL,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=TRADE_QUANTITY_SELL)
print(order)
...the code rounds to a precision of 5 decimal points, while in the code that doesn't work...
import websocket, json, pprint, talib, numpy
import config
from binance.client import Client
from binance.enums import *
SOCKET = "wss://stream.binance.com:9443/ws/btceur#kline_5m"
RSI_PERIOD = 14
RSI_OVERBOUGHT = 70
RSI_OVERSOLD = 30
TRADE_SYMBOL = 'BTCEUR'
TRADE_QUANTITY_BUY = 0.002
closes = []
client = Client(config.API_KEY, config.API_SECRET)
balance = client.get_asset_balance(asset='BTC')
FREEBTC = float(balance['free'])
TRADE_QUANTITY_SELL = round(FREEBTC, 6)
#print(SELL_TOTAL)
# ...
...it rounds to a precision of 6 decimal points. TRADE_QUANTITY_BUY is at a precision of 3 decimal points; less precise than both. To me, this suggests that perhaps a transaction of lesser than 0.00001 for your particular "coin" at a time is invalid through your API, causing them to be blocked.
My advice: check that the binance library you are using supports sell orders of that amount, since sell orders they may be filtered.
This all comes from a quick search: this library you are using may have more specific information on minimum/maximum order prices.
I am trying to execute the code of pyethereum but when I was analyzing the code in
pyethereum/Ethereum/hybrid_casper/consenus.py
I can't understand where the 'NULL_SENDER' value is defined and how this state.config['NULL_SENDER] will execute.
key, account = state.config['NULL_SENDER'], privtoaddr(state.config['NULL_SENDER'])
Let's look through all the code.
from ethereum import utils, transactions
from ethereum.common import update_block_env_variables
from ethereum.messages import apply_transaction
from ethereum.hybrid_casper import casper_utils
from ethereum.utils import privtoaddr
# Block initialization state transition
def initialize(state, block=None):
config = state.config
state.txindex = 0
state.gas_used = 0
state.bloom = 0
state.receipts = []
if block is not None:
update_block_env_variables(state, block)
# Initalize the next epoch in the Casper contract
if state.block_number % state.config['EPOCH_LENGTH'] == 0 and state.block_number != 0:
key, account = state.config['NULL_SENDER'], privtoaddr(state.config['NULL_SENDER'])
data = casper_utils.casper_translator.encode('initialize_epoch', [state.block_number // state.config['EPOCH_LENGTH']])
transaction = transactions.Transaction(state.get_nonce(account), 0, 3141592,
state.config['CASPER_ADDRESS'], 0, data).sign(key)
success, output = apply_transaction(state, transaction)
assert success
if state.is_DAO(at_fork_height=True):
for acct in state.config['CHILD_DAO_LIST']:
state.transfer_value(
acct,
state.config['DAO_WITHDRAWER'],
state.get_balance(acct))
if state.is_METROPOLIS(at_fork_height=True):
state.set_code(utils.normalize_address(
config["METROPOLIS_STATEROOT_STORE"]), config["METROPOLIS_GETTER_CODE"])
state.set_code(utils.normalize_address(
config["METROPOLIS_BLOCKHASH_STORE"]), config["METROPOLIS_GETTER_CODE"])
We can see that this code is most likely being imported by multiple programs, which it is! https://github.com/ethereum/pyethereum/blob/develop/ethereum/hybrid_casper/chain.py
If we see the usage of the function in chain.py, the state parameter is being fulfilled with self.state, it is self.state = self.mk_poststate_of_blockhash(self.db.get(b'head_hash')).
This function returns a State object, made in ethereum.state, which can be turned into a dictionary. This most likely means that it is getting the value that corresponds to the key called 'NULL_SENDER'.
I have a written a script that uses the code below and I would like to optimize rsi_high and rsi_low to get the best sharpe_ratio:
#
import numpy
import talib as ta
global rsi_high, rsi_low
rsi_high = 63
rsi_low = 41
def myTradingSystem(DATE, OPEN, HIGH, LOW, CLOSE, VOL, exposure, equity, settings):
''' This system uses trend following techniques to allocate capital into the desired equities'''
nMarkets = CLOSE.shape[1] # SHAPE OF NUMPY ARRAY
result, rsi_pos = numpy.apply_along_axis(rsicalc, axis=0, arr=CLOSE)
pos = numpy.asarray(rsi_pos, dtype=numpy.float64)
return pos, settings
def rsicalc(num):
# print rsi_high
try:
rsival = ta.RSI(numpy.array(num,dtype='f8'),timeperiod=14)
if rsival[14] > rsi_high: pos_rsi = 1
elif rsival[14] < rsi_low: pos_rsi = -1
else: pos_rsi = 0
except:
rsival = 0
pos_rsi = 0
return rsival, pos_rsi
def mySettings():
''' Define your trading system settings here '''
settings = {}
# Futures Contracts
settings['markets'] = ['CASH','F_AD', 'F_BO', 'F_BP', 'F_C', 'F_CC', 'F_CD',
'F_CL', 'F_CT', 'F_DX', 'F_EC', 'F_ED', 'F_ES', 'F_FC', 'F_FV', 'F_GC',
'F_HG', 'F_HO', 'F_JY', 'F_KC', 'F_LB', 'F_LC', 'F_LN', 'F_MD', 'F_MP',
'F_NG', 'F_NQ', 'F_NR', 'F_O', 'F_OJ', 'F_PA', 'F_PL', 'F_RB', 'F_RU',
'F_S', 'F_SB', 'F_SF', 'F_SI', 'F_SM', 'F_TU', 'F_TY', 'F_US', 'F_W',
'F_XX', 'F_YM']
settings['slippage'] = 0.05
settings['budget'] = 1000000
settings['beginInSample'] = '19900101'
settings['endInSample'] = '19931231'
settings['lookback'] = 504
return settings
# Evaluate trading system defined in current file.
if __name__ == '__main__':
import quantiacsToolbox
results = quantiacsToolbox.runts(__file__, plotEquity=False)
sharpe_ratio = results['stats']['sharpe']
I suspect that using something like scipy minimize function would do the trick, but I am having trouble understanding how to package my script so that it can be in a usable form.
I have tried putting everything in a function and then running all the code through a number of loops, each time incrementing values but there must be a more elegant way of doing this.
Apologies for posting all my code but I thought it would help if the responder wanted to reproduce my setup and for anyone who is new to quantiacs to see a real example who is faced with the same issue.
Thanks for your help in advance!