side = data['strategy']['order_action'].upper()
quantity = data['strategy']['order_contracts']
ticker = data['ticker']
curposition =data['strategy']['market_position']
if (curposition=='long'):
order('buy',quantity,ticker)
elif(curposition=='short'):
order('sell',quantity,ticker)
elif(curposition=='flat'):
bitget.post_closeTrackOrder(symbol='ETHUSDT_UMCBL',trackingNo='currentTrack')
**strong text**
here is my python code and idk what to use in close copytrade positions..
PS:i`m using bitget now.
Related
Please can anyone advise how I may retrieve FX Forwards NDF's outright bid / outright ask or indeed any price data for USD/KRW for the 1W, 1M, 3M etc tenors.
I have attempted to follow the DAPI instructions as well as attempting to find answers via Stackoverflow to no avail. I can however succesfully retrieve live bid asks for SPOT USD KRW or even Equities such as AAPL no problem
I have tried using different combinations of the tickers, although I see no error codes no actual live prices come back? Please does anyone have any ideas to get live ticking NDF outright prices:
Any & all help is greatly appreciated :) as Bloomberg seemingly don't provide any assistance
['USD/KRW N 2M Curncy'], ['USD/KRW N 3M Curncy'] , ['USD/KRW N 3M ICAP Curncy']
p.s the Excel Bloomberg formula such as =BFxForward("USDKRW","3M","BidOutright") is essentially what I'm trying to replicate via python, attempting to follow the DAPI instructions seems to not work.
I have used the C++ BLPAPI pdf examples to attempt to get this working however no NDF examples seemingly exist.
def main_subscribe():
tickers = ['USD/KRW N 2M Curncy', 'USD/KRW N 6M Curncy', 'USD/KRW N 9M Curncy']
fields = ['BID', 'LAST_BID_TIME_TODAY_REALTIME', 'ASK','MID']
interval = 2
options = parseCmdLine()
# Fill SessionOptions
sessionOptions = blpapi.SessionOptions()
sessionOptions.setServerHost(options.host)
sessionOptions.setServerPort(options.port)
print("Connecting to %s:%s" % (options.host, options.port))
# Create a Session
session = blpapi.Session(sessionOptions)
# Start a Session
if not session.start():
print("Failed to start session.")
return
try:
# Open service to get subscription data from
if not session.openService('//blp/mktdata'):
print("Failed to open '//blp/mktdata")
return
# init subscriptions
subs = blpapi.SubscriptionList()
flds = ','.join(fields)
istr = interval and 'interval=%.1f' % interval or ''
for ticker in tickers:
subs.add(ticker, flds, istr, blpapi.CorrelationId(ticker))
session.subscribe(subs)
# Process received events
while(True):
# We provide timeout to give the chance for Ctrl+C handling:
ev = session.nextEvent(900)
for msg in ev:
print(msg)
# if ev.eventType() == blpapi.Event.SUBSCRIPTION_DATA:
# try:
# for msg in ev:
# #print(msg)
# print(f"{fields[0]}:{msg.getElementAsString(fields[0])} , {fields[3]}:{msg.getElementAsString(fields[3])} , {fields[2]}:{msg.getElementAsString(fields[2])} , {fields[1]}:{msg.getElementAsString(fields[1])}")
# except Exception as e:
# print(e)
# #print(msg)
# None
finally:
# Stop the session
session.stop()
This is the output when main-subscribe is run:
CID: {[ valueType=POINTER classId=0 value=0000024DBF510CB0 ]}
RequestId: -----------------------------
MarketDataEvents = {
MKTDATA_EVENT_TYPE = SUMMARY
MKTDATA_EVENT_SUBTYPE = INITPAINT
API_RULES_VERSION = 201411210
SIMP_LAST_PX_ALL_SESS_DIR_RT = 1
SMART_FIELDS_METADATA_VERSION_RT = "21.10.08.02 "
IS_DELAYED_STREAM = false
MID = 1.000000
RT_API_MACHINE = "apipubx0#----------"
RT_YLD_CHG_NET_1D = 0.000000
IND_BID_FLAG = false
IND_ASK_FLAG = false
BASE_PRICE_ENABLED_RT = false
EVT_DELTA_TIMES_RT = 0
ALL_PRICE_COND_CODE = ""}
This is the KRW <Curncy> FRD <Go> screen in the Bloomi Terminal:
If you hover the mouse over the 3M outright Bid (in the circle), the pop-up shows the underlying ticker to be KWN+3M BGN Curncy.
When I put this ticker in Excel as:
=BDP("KWN+3M BGN Curncy","BID","UpdateFrequency",500) then I get updating bid side pricing which matches the Terminal screen.
Since the underlying DAPI for Excel and Python is the same, I would guess that this ticker will work with the blpapi too. I usually find it is quicker to test tickers and fields in Excel.
I am running a python script to fetch all the current order books for all symbols that ends with USDT.
Whenever I try to run it, it fetches the orderbook for the first three symbols (in this case BTCUSDT, ETHUSDT and BNBUSDT). Any takers on what I am messing up here?
I am using this logic to get a list of the symbols and the order book;
import asyncio
import config as c #from config.py
import infinity as inf #userdefined function for infinity (probably not needed)
from binance import AsyncClient, DepthCacheManager, Client
client = Client(c.API_KEY, c.API_SECRET, tld = 'com')
info = client.get_exchange_info()
symbols = info['symbols']
ls = []
for s in symbols:
if 'USDT' in s['symbol']:
#if 'BUSD' not in s['symbol']:
ls.append(s['symbol'])
async def main():
# initialise the client
client = await AsyncClient.create()
for i in ls:
async with DepthCacheManager(client, symbol= i, limit = 10000) as dcm_socket:
depth_cache = await dcm_socket.recv()
symbol = i
asks = depth_cache.get_asks()[:5]
bids = depth_cache.get_bids()[:5]
full = [symbol, asks, bids]
print(full)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
It wouldn't complete, because it's not supposed to.
DepthCacheManager is designed to establish a connection (WebSockets), get a snapshot of the order information, and then subscribes to a stream of updates to the current outstanding orders that it applies locally in it's "DepthCache". Each time that gets updated, it deliver the updated set of current asks/bids as you can see.
The trading and orders never stop, so why would it stop?
Maybe you wana try: https://github.com/LUCIT-Systems-and-Development/unicorn-binance-local-depth-cache
import unicorn_binance_local_depth_cache
ubldc = unicorn_binance_local_depth_cache.BinanceLocalDepthCacheManager(exchange="binance.com")
ubldc.create_depth_cache("LUNABTC")
asks = ubldc.get_asks("LUNABTC")
bids = ubldc.get_bids("LUNABTC")
Thats it :)
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
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
This code correctly gets a live quote from Interactive Brokers, and then sends it to a csv text file with the current price. Now, how do I make this code automatically keep running? I am doing a sleep command every 15 seconds.
import csv
from ib_insync import *
stocks = ['TVIX']
test = list()
for stock in stocks:
stock = Stock(stock, 'SMART','USD')
contract = ib.qualifyContracts(stock)
test.append(ib.reqMktData(contract[0],snapshot=True))
ib.sleep(15)
for stock in test:
f = open('tvix-price.csv','w')
f.write(str(stock.last))
f.close()
Below is my code of what I have so far...
I get no errors which is kind of strange. Nothing at all happens. I will attempt to restart my Kernal to make sure I am connected.
On second thought, is doing a while True even the best method?
while True:
stocks = ['TVIX']
test = list()
for stock in stocks:
stock = Stock(stock, 'SMART','USD')
contract = ib.qualifyContracts(stock)
test.append(ib.reqMktData(contract[0],snapshot=True))
ib.sleep(15)
for stock in test:
f = open('tvix-price.csv','w')
f.write(str(stock.last))
f.close()
Part of your code wasn't indented correctly, and you put the wrong part in the loop.
You should have done:
import csv
from ib_insync import *
stocks = ['TVIX']
while True:
test = list()
for stock in stocks:
stock = Stock(stock, 'SMART','USD')
contract = ib.qualifyContracts(stock)
test.append(ib.reqMktData(contract[0],snapshot=True))
ib.sleep(15)
for stock in test:
f = open('tvix-price.csv','w')
f.write(str(stock.last))
f.close()
The while True loop only repeats the indented section. As part of your code was not indented beyond the loop, it wasn't run.
Hope this helps.