It is said that shock body is very eye-catching, today I will try 🤪
All articles in this series begin with a sentence or two summarizing the content of the corresponding article. If you’re interested in this topic, you can read on. If you’re not, you can turn it off without wasting your time.
conclusion
This article uses Python to implement a simple automatic transaction script, which will be automatically notified by wechat when the transaction is generated.
Involving the concept | The concept content |
---|---|
Python library |
Wechaty |
The main concept | Quantitative trading, wechat robot |
Quantitative trading
Introduction to the
In July, the good market of big A shares must be deeply impressed by everyone, and some people even predict that A five or six years of A cycle of big bull market is about to open.
You’ve already seen the results, but whether it was on or not, most people’s brains were pretty hot, including mine. However, looking back on my miserable investment experience, the words “chase the upside kill the downside” are a good summary 😂.
This is difficult to handle, helplessly watching others make money double, I do not make money is equivalent to then lose money.
I am well aware that every trading decision I make is a reflection of my own emotions, and the consequence of emotional trading is to chase up gains and lose money. So the question is, how can I control my losing hands? One answer may be quantitative trading.
Quantitative trading is not a very sophisticated concept.
A quantitative trading software will buy and sell according to a defined trading strategy, which is completely triggered by the strategy and not controlled by humans.
The simplest trading strategies are double mean strategy, grid trading strategy and so on.
This is the way the deal was designed for me, so mom doesn’t have to worry about my smelly hands anymore.
Grid trading strategy
There are many quant trading frameworks available online, but learning them can take a long time. Anyway, I just want to do a quick test, and familiarize myself with the mechanics of the strategy, so I’ll just write one freehand.
What exactly is grid trading? Grid transactions can be simply understood as:
Put the price range in a set grid, the capital divided into many, each price drop to buy a block, each block to sell a block. A buy corresponding to a sell, between the sale of a grid to earn only the price difference.
Looks like it’s exactly what I need. Grid trading is more suitable for the target with higher oscillation frequency and greater amplitude; Make only one square of money at a time, every little makes a mickle. By dividing your money into pieces, you’re less efficient, but also less risky.
Without further delay, I decided to test the grid trading strategy.
First of all, we need to define a pre-defined oscillation interval and mesh number. I put these pre-defined parameters into a special configuration file:
lowest = 2.5 # Grid lowest price
highest = 3.5 # Maximum grid price
parts = 20 # grid number
start_value = 300.0 # Initial fund of account
timespan = 15 Check the bid price every 15 seconds
wechat_reminder = 1 # Whether to notify via wechat (1: yes, 0: no)
mail_reminder = 0 # Whether to notify by email (1: yes, 0: no)
mail_list = ['mailbox1',]List of email addresses to be notified
Copy the code
At initialization, the script sets the current grid according to the configuration:
# Height of each grid
price_part_value = (highest - lowest) / parts
# The percentage of positions held for each block change
percent_part_value = 1 / parts
# Tag price for all grids
price_levels = [round(highest - index * price_part_value, 4) for index in range(parts + 1)]
price_levels[-1] = lowest
# Total position percentage for each column
percent_levels = [round(0 + index * percent_part_value, 4) for index in range(parts + 1)]
percent_levels[-1] = 1.0000
Copy the code
After completing the configuration, it is necessary to build the base warehouse according to the current price of the target:
# If the current price is higher than the lowest grid price, the number of storehouses will be calculated according to the grid; otherwise, the storehouse will be filled directly
# order_target_percent Determine whether to buy or sell according to the symbol and value of target, and place the order
if float(close) > price_levels[0]:
pos = [close > level for level in price_levels]
i = pos.index(False) - 1
last_price_index = i
target = percent_levels[last_price_index] - last_percent
iftarget ! =0.0:
return True, order_target_percent(float(close), depth, target, date=date)
else:
return True, order_target_percent(float(close), depth, 1.0, date=date)
Copy the code
Then perform the corresponding operation each time the bid price passes through the grid:
signal = False
while True:
upper = None
lower = None
if last_price_index > 0:
upper = price_levels[last_price_index - 1]
if last_price_index < len(price_levels) - 1:
lower = price_levels[last_price_index + 1]
# is not the lightest position, continue to rise, sell another gear
if upper and float(close) > upper:
last_price_index = last_price_index - 1
signal = True
continue
# Not the heaviest position, continue to fall, buy another
if lower and float(close) < lower:
last_price_index = last_price_index + 1
signal = True
continue
break
if signal:
target = percent_levels[last_price_index] - last_percent
iftarget ! =0.0:
return True, order_target_percent(float(close), depth, target, date=date)
else:
return FalseAnd []Copy the code
At this point a simple but very complete grid trading strategy is written. Of course, it is up to the reader to obtain real-time prices and implement trading operations.
Wechat robot
This article is from Titus cosmos on wechat. The ID is TitusCosmos.
In order to prevent all kinds of crawlers on the Internet from crawling and deliberately delete the original author information, so in the middle of the article to join the author information, but also hope that readers understand.
Introduction to the
As those of you who have read my previous posts know, ALL of my posts on wechat bots have been written using ItChat. This library only supports the wechat signal that can log in to the webpage version of wechat. The wechat signal that did not log in to the webpage version of wechat before 2017 and the new wechat signal that applied after 2017 basically cannot be used, the limitation is too big! Readers can check whether they can use web-based wechat at https://wx.qq.com/.
After much searching, I finally found a library that is not limited to the web version of wechat: Wechaty:
Wechaty was originally developed in TypeScript, but the team is working on a multilingual port. A Python version is available, though it may not be as powerful as the original. The Wechaty team is committed to developing a library that supports the full range of wechat protocols, including Web, Ipad, Windows, and Mac protocols. Although there is a fee to obtain tokens, you can apply to participate in the open source incentive program to obtain free or even long-term tokens. Thanks also to the Wechaty team for providing the wechat robot SDK🙏🙏🙏.
Demo
Let’s implement a simple robot: after receiving any message, reply received.
import asyncio
from typing import Optional.Union
from wechaty import Wechaty, Contact
from wechaty.user import Message, Room
async def wechat() :
bot = Wechaty()
Bind the on_message method to the bot object's message event
bot.on('message', on_message)
await bot.start()
async def on_message(msg: Message) :
from_contact = msg.talker()
text = msg.text()
room = msg.room()
conversation: Union[
Room, Contact] = from_contact if room is None else room
await conversation.ready()
await conversation.say('received')
asyncio.run(wechat())
Copy the code
Wechaty also provides many event interfaces, such as Scan, login, Room-Join, Room-leave, logout, and error.
Use in scripts
The above demo code is very simple and easy to understand, and it is also very simple to use in this case.
When the current price triggers the grid strategy to trade, it only needs to summarize the information of the next trade after the trade, and then send it out using the method similar to the above. In practice, I would send the corresponding message to my specially built “quantified live broadcast” group (there are two grids currently in operation) :
async def on_message(msg: Message) :
from_contact = msg.talker()
text = msg.text()
room = msg.room()
conversation: Union[
Room, Contact] = from_contact if room is None else room
if from_contact.payload.name.upper() == AdminWechatName and from_contact.contact_id.upper() == AdminWechatContactId:
Return current grid position status when sending #GRIDSTATUS
if text.upper() == '#GRIDSTATUS':
await conversation.ready()
await conversation.say(str(grid))
# send #SETGRID: Dynamically modify grid parameters when formatting information
elif text.upper().startswith('#SETGRID:'):
paras = {('grid.' + item.split('=') [0]): item.split('=') [1] for item in text[9:].lower().split('; ')}
cfg.set_paras(paras)
await run_grid()
async def run_grid() :
flag, content = grid.run_data(data)
if flag:
if int(grid.mail_reminder):
for mail_box in grid.mail_list:
mail_helper.sendmail(mail_box, 'GRID SCRIPT NEW TRADE', content)
if int(grid.wechat_reminder):
await trade_reminder(bot, content)
async def trade_reminder(bot, mail_content, target=None) :
for id in target:
room = bot.Room.load(id)
await room.ready()
conversation: Union[Room, Contact] = room
await conversation.ready()
await conversation.say(mail_content)
Copy the code
Here’s the actual effect:
An alternative to wechat robots
I’m sure some readers will find the above robot too troublesome, here is a recommended small tool, but also thanks to the developer’s efforts and dedication!
This tool is called Server Sauce, ServerChan in English. It is a communication software between programmer and Server. It is a tool that pushes alarms and logs from Server to mobile phone. The official website is sc.ftqq.com/3.version, readers can understand, in short, very easy to use it.
It only takes a minute to open and use:
-
Login: Log into the site with your GitHub account and get an SCKEY.
-
Binding: Click “wechat push” to complete binding at the same time.
-
Message: send a GET request to http://sc.ftqq.com/SCKEY.send, you can received the message in the WeChat.
Messages came in like this:
Is it simple and convenient?
P.S.
Grid trading strategy is more suitable for volatile markets, so the strategy is currently implemented on digital currencies, including a solid currency and a test currency, digital currency readers should be aware of its volatile market.
Readers who are interested can also contact me to further quantify the dynamic broadcast group. When the grid transaction is triggered, the robot will send the operation dynamic to the group in real time.
Afterword.
No matter what I write, I hope to communicate with more people. If you have any questions or needs, please feel free to communicate.
All of my project source code will be placed in the following github warehouse, there is a need for reference, welcome to point out the problem, thank you!
https://github.com/TitusWongCN/
Copy the code
Here is my official account, I can scan it if I am interested: