PluginInstance.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. #include "pch.h"
  2. #include "PluginInstance.h"
  3. #define REDIS_TIMER_ID (1)
  4. CPluginInstance::CPluginInstance()
  5. : m_enable(false)
  6. , m_redis_error_notified(false)
  7. {
  8. }
  9. CPluginInstance::~CPluginInstance()
  10. {
  11. Stop();
  12. }
  13. void CPluginInstance::Release()
  14. {
  15. delete this;
  16. }
  17. MTAPIRES CPluginInstance::Start(IMTServerAPI * server)
  18. {
  19. MTAPIRES ret = MT_RET_OK;
  20. if (!server) return MT_RET_ERR_PARAMS;
  21. m_api = server;
  22. if ((m_config = m_api->PluginCreate()) == nullptr)
  23. return MT_RET_ERR_MEM;
  24. ret = m_api->About(m_info);
  25. if (ret != MT_RET_OK)
  26. m_api->LoggerOut(MTLogOK, L"Server info failed [%d]", ret);
  27. if ((ret = m_api->PluginSubscribe(this)) != MT_RET_OK)
  28. {
  29. m_api->LoggerOut(MTLogAtt, L"Plugin subscribe failed [%d]", ret);
  30. return ret;
  31. }
  32. if (ret = m_api->OrderSubscribe(this) != MT_RET_OK)
  33. {
  34. m_api->LoggerOut(MTLogAtt, L"Order subscribe failed [%d]", ret);
  35. return ret;
  36. }
  37. if (ret = m_api->DealSubscribe(this) != MT_RET_OK)
  38. {
  39. m_api->LoggerOut(MTLogAtt, L"Deal subscribe failed [%d]", ret);
  40. return ret;
  41. }
  42. if ((ret = LoadParam()) != MT_RET_OK)
  43. {
  44. m_api->LoggerOut(MTLogAtt, L"Load param failed [%d]", ret);
  45. return ret;
  46. }
  47. return MT_RET_OK;
  48. }
  49. MTAPIRES CPluginInstance::Stop()
  50. {
  51. MTAPIRES ret = MT_RET_OK;
  52. std::lock_guard<decltype(m_lock)> lk(m_lock);
  53. m_followers.clear();
  54. if (m_api == nullptr)
  55. return MT_RET_OK;
  56. if (m_config != nullptr)
  57. {
  58. m_config->Release();
  59. m_config = nullptr;
  60. }
  61. if ((ret = m_api->PluginUnsubscribe(this)) != MT_RET_OK && ret != MT_RET_ERR_NOTFOUND)
  62. m_api->LoggerOut(MTLogErr, L"failed to unsubscribe from plugin config updates [%s (%u)]",
  63. SMTFormat::FormatError(ret), ret);
  64. if ((ret = m_api->OrderUnsubscribe(this)) != MT_RET_OK && ret != MT_RET_ERR_NOTFOUND)
  65. m_api->LoggerOut(MTLogErr, L"failed to unsubscribe order [%s (%u)]",
  66. SMTFormat::FormatError(ret), ret);
  67. if ((ret = m_api->DealUnsubscribe(this)) != MT_RET_OK && ret != MT_RET_ERR_NOTFOUND)
  68. m_api->LoggerOut(MTLogErr, L"failed to unsubscribe deal [%s (%u)]",
  69. SMTFormat::FormatError(ret), ret);
  70. m_api = nullptr;
  71. m_enable = false;
  72. stop_redis();
  73. if (m_work_thread.joinable())
  74. m_work_thread.join();
  75. return MT_RET_OK;
  76. }
  77. void CPluginInstance::OnPluginUpdate(const IMTConPlugin * plugin)
  78. {
  79. int ret = MT_RET_OK;
  80. if ((ret = LoadParam()) != MT_RET_OK)
  81. {
  82. m_api->LoggerOut(MTLogAtt, L"Load param failed [%d]", ret);
  83. }
  84. }
  85. //void CPluginInstance::OnOrderAdd(const IMTOrder * order)
  86. //{
  87. // if (order == nullptr) return;
  88. //
  89. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  90. // if (!m_enable) return;
  91. // if (order->Login() != m_trader) return;
  92. //
  93. // m_api->LoggerOut(MTLogOK, L"OnOrderAdd, login: %lld, ord: %lld, pos: %lld, state: %lld, vol_init: %lld, vol_cur: %lld",
  94. // order->Login(), order->Order(), order->PositionID(), order->State(), order->VolumeInitial(), order->VolumeCurrent());
  95. //}
  96. //void CPluginInstance::OnOrderUpdate(const IMTOrder * order)
  97. //{
  98. // if (order == nullptr) return;
  99. //
  100. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  101. // if (!m_enable) return;
  102. // if (order->Login() != m_trader) return;
  103. //
  104. // m_api->LoggerOut(MTLogOK, L"OnOrderAdd, login: %lld, ord: %lld, pos: %lld, state: %lld, vol_init: %lld, vol_cur: %lld",
  105. // order->Login(), order->Order(), order->PositionID(), order->State(), order->VolumeInitial(), order->VolumeCurrent());
  106. //}
  107. void CPluginInstance::OnOrderDelete(const IMTOrder * order)
  108. {
  109. if (order == nullptr) return;
  110. std::lock_guard<decltype(m_lock)> lk(m_lock);
  111. if (!m_enable) return;
  112. if (order->Login() != m_trader) return;
  113. m_api->LoggerOut(MTLogOK, L"OnOrderDelete, login: %lld, ord: %lld, pos: %lld, state: %d, vol_init: %lld, vol_cur: %lld",
  114. order->Login(), order->Order(), order->PositionID(), order->State(), order->VolumeInitial(), order->VolumeCurrent());
  115. if (order->Type() != IMTOrder::OP_BUY
  116. && order->Type() != IMTOrder::OP_SELL)
  117. {
  118. // 不是buy或者sell,不跟,直接退出
  119. return;
  120. }
  121. char order_buf[128];
  122. sprintf(order_buf, "%lld", order->PositionID());
  123. IMTAccount* account = m_api->UserCreateAccount();
  124. IMTOrder* new_order = m_api->OrderCreate();
  125. ScopeGuard guard([account, new_order]
  126. {
  127. if (account)
  128. account->Release();
  129. if (new_order)
  130. new_order->Release();
  131. });
  132. // 订单在进入filled状态时,也会产生一个order delete回调
  133. if (order->Order() == order->PositionID())
  134. {
  135. // 如果是新建订单,那么写入新纪录
  136. char login_buf[128];
  137. for (auto login : m_followers)
  138. {
  139. if (m_api->UserAccountGet(login, account) != MT_RET_OK)
  140. {
  141. // TODO: 这里失败直接跳过没有做其他处理,下一次进来可能依然会遇到一样的问题
  142. continue;
  143. }
  144. sprintf(login_buf, "%lld", login);
  145. UINT level = (UINT)(account->Balance() / m_step);
  146. UINT volume = round((double)level * order->VolumeCurrent() / 10000) * 100;
  147. UINT volume_ext = round((double)level * order->VolumeCurrentExt() / 10000) * 100;
  148. UINT init_volume = round((double)level * order->VolumeInitial() / 10000) * 100;
  149. UINT init_volume_ext = round((double)level * order->VolumeInitialExt() / 10000) * 100;
  150. UINT64 new_order_id = 0;
  151. m_api->LoggerOut(MTLogOK, L"add order, vol_init: %lld, vol_cur: %lld", init_volume, volume);
  152. // 尚未完成建仓,目前position id不填,仅完成订单后记录
  153. new_order->Clear();
  154. new_order->VolumeInitial(init_volume);
  155. new_order->VolumeCurrent(volume);
  156. new_order->Login(login);
  157. new_order->Symbol(order->Symbol());
  158. new_order->Type(order->Type());
  159. new_order->Digits(order->Digits());
  160. new_order->DigitsCurrency(order->DigitsCurrency());
  161. new_order->ContractSize(order->ContractSize());
  162. new_order->PriceOrder(order->PriceOrder());
  163. new_order->PriceCurrent(order->PriceCurrent());
  164. new_order->StateSet(order->State());
  165. new_order->TimeSetup(order->TimeSetup());
  166. new_order->TimeSetupMsc(order->TimeSetupMsc());
  167. new_order->TimeDone(order->TimeDone());
  168. new_order->TimeDoneMsc(order->TimeDoneMsc());
  169. // --
  170. new_order->PriceSL(order->PriceSL());
  171. new_order->PriceTP(order->PriceTP());
  172. new_order->Comment(order->Comment());
  173. new_order->ActivationFlags(order->ActivationFlags());
  174. new_order->ActivationMode(order->ActivationMode());
  175. new_order->ActivationPrice(order->ActivationPrice());
  176. new_order->ActivationTime(order->ActivationTime());
  177. new_order->PriceTrigger(order->PriceTrigger());
  178. new_order->RateMargin(order->RateMargin()); //
  179. new_order->ReasonSet(order->Reason()); //
  180. new_order->TypeFill(order->TypeFill()); //
  181. new_order->TypeTime(order->TypeTime()); //
  182. MTAPIRES ret = m_api->HistoryAdd(new_order);
  183. if (ret != MT_RET_OK)
  184. {
  185. m_api->LoggerOut(MTLogErr, L"%lld failed to add order, original order #%lld [%d]", login, order->Login(), ret);
  186. }
  187. else
  188. {
  189. new_order_id = new_order->Order();
  190. }
  191. m_api->LoggerOut(MTLogOK, L"%lld add order #%lld, original order #%lld [%d]", login, new_order_id, order->Order());
  192. // TODO: 现在做法是,如果level为0,后面都不管
  193. // 如果跟单失败,那么position id也为0,所以后面也不应该处理
  194. position_context context;
  195. context.level = level;
  196. context.cur_ord = new_order_id;
  197. context.position_id = new_order_id; // 建仓,order id = position id
  198. int direction = 1;
  199. if (order->Type() == IMTOrder::OP_SELL)
  200. direction = -1;
  201. context.volume = direction * order->VolumeInitial();
  202. m_redis_client->hset(order_buf, login_buf, std::string((char*)&context, sizeof(position_context)), [this](cpp_redis::reply& r)
  203. {
  204. if (r.ko())
  205. {
  206. m_api->LoggerOut(MTLogErr, L"redis: %s", r.error().c_str());
  207. }
  208. });
  209. m_redis_client->commit();
  210. }
  211. }
  212. else
  213. {
  214. // 如果不是新建订单,先使用position id先检查记录是否存在
  215. char login_buf[128];
  216. for (auto login : m_followers)
  217. {
  218. sprintf(login_buf, "%lld", login);
  219. auto fut = m_redis_client->hget(order_buf, login_buf);
  220. m_redis_client->sync_commit();
  221. auto reply = fut.get();
  222. m_api->LoggerOut(MTLogOK, L"request cache, key %s, field %s", s2ws(order_buf).c_str(), s2ws(login_buf).c_str());
  223. // 如果不存在,忽略
  224. if (reply.ko()) continue;
  225. if (reply.is_null()) continue;
  226. m_api->LoggerOut(MTLogOK, L"get context, login: %lld", login);
  227. // 获取context
  228. position_context context;
  229. memcpy(&context, reply.as_string().c_str(), sizeof(position_context));
  230. // 按建仓时的叙述,如果level或者position为0,亦忽略该记录
  231. if (context.level == 0) continue;
  232. if (context.position_id == 0) continue;
  233. m_api->LoggerOut(MTLogOK, L"get context, order: #%lld, position: #%lld", context.cur_ord, context.position_id);
  234. // 如果存在,则继续操作
  235. UINT volume = round((double)context.level * order->VolumeCurrent() / 10000) * 100;
  236. UINT volume_ext = round((double)context.level * order->VolumeCurrentExt() / 10000) * 100;
  237. UINT init_volume = round((double)context.level * order->VolumeInitial() / 10000) * 100;
  238. UINT init_volume_ext = round((double)context.level * order->VolumeInitialExt() / 10000) * 100;
  239. UINT64 new_order_id = 0;
  240. new_order->Clear();
  241. new_order->VolumeInitial(init_volume);
  242. new_order->VolumeCurrent(volume); // 这里是状态START,如果是状态4的FILLED时,volume current为0
  243. //new_order->VolumeCurrent(init_volume);
  244. new_order->Login(login);
  245. new_order->Symbol(order->Symbol());
  246. new_order->Type(order->Type());
  247. new_order->Digits(order->Digits());
  248. new_order->DigitsCurrency(order->DigitsCurrency());
  249. new_order->ContractSize(order->ContractSize());
  250. new_order->PriceOrder(order->PriceOrder());
  251. new_order->PriceCurrent(order->PriceCurrent());
  252. new_order->StateSet(order->State());
  253. new_order->TimeSetup(order->TimeSetup());
  254. new_order->TimeSetupMsc(order->TimeSetupMsc());
  255. new_order->TimeDone(order->TimeDone());
  256. new_order->TimeDoneMsc(order->TimeDoneMsc());
  257. new_order->PositionID(context.position_id);
  258. new_order->PriceSL(order->PriceSL());
  259. new_order->PriceTP(order->PriceTP());
  260. new_order->Comment(order->Comment());
  261. new_order->ActivationFlags(order->ActivationFlags());
  262. new_order->ActivationMode(order->ActivationMode());
  263. new_order->ActivationPrice(order->ActivationPrice());
  264. new_order->ActivationTime(order->ActivationTime());
  265. new_order->PriceTrigger(order->PriceTrigger());
  266. new_order->RateMargin(order->RateMargin()); //
  267. new_order->ReasonSet(order->Reason()); //
  268. new_order->TypeFill(order->TypeFill()); //
  269. new_order->TypeTime(order->TypeTime()); //
  270. MTAPIRES ret = m_api->HistoryAdd(new_order);
  271. if (ret != MT_RET_OK)
  272. {
  273. m_api->LoggerOut(MTLogErr, L"%lld failed to add order, original order #%lld [%d]", login, order->Order(), ret);
  274. // FIXME: 如果做单失败该怎么办
  275. continue;
  276. }
  277. new_order_id = new_order->Order();
  278. m_api->LoggerOut(MTLogOK, L"%lld add order #%lld, original order #%lld", login, new_order_id, order->Order());
  279. // 完成之后,写入新纪录
  280. context.cur_ord = new_order_id;
  281. int direction = 1;
  282. if (order->Type() == IMTOrder::OP_SELL)
  283. direction = -1;
  284. context.volume += direction * order->VolumeInitial();
  285. m_api->LoggerOut(MTLogOK, L"write cache, key %s, field %s", s2ws(order_buf).c_str(), s2ws(login_buf).c_str());
  286. m_redis_client->hset(order_buf, login_buf, std::string((char*)&context, sizeof(position_context)), [this](cpp_redis::reply& r)
  287. {
  288. if (r.ko())
  289. {
  290. m_api->LoggerOut(MTLogErr, L"redis: %s", r.error().c_str());
  291. }
  292. });
  293. m_redis_client->commit();
  294. }
  295. }
  296. }
  297. //void CPluginInstance::OnOrderClean(const UINT64 login)
  298. //{
  299. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  300. // if (!m_enable) return;
  301. // if (login != m_trader) return;
  302. //
  303. // m_api->LoggerOut(MTLogOK, L"OnOrderClean, Login: %d", login);
  304. //}
  305. //void CPluginInstance::OnDealAdd(const IMTDeal * deal)
  306. //{
  307. // if (deal == nullptr) return;
  308. //
  309. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  310. // if (!m_enable) return;
  311. // if (deal->Login() != m_trader) return;
  312. //
  313. // m_api->LoggerOut(MTLogOK, L"OnDealAdd, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  314. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  315. //}
  316. //void CPluginInstance::OnDealUpdate(const IMTDeal * deal)
  317. //{
  318. // if (deal == nullptr) return;
  319. //
  320. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  321. // if (!m_enable) return;
  322. // if (deal->Login() != m_trader) return;
  323. //
  324. // m_api->LoggerOut(MTLogOK, L"OnDealUpdate, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  325. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  326. //}
  327. //void CPluginInstance::OnDealDelete(const IMTDeal * deal)
  328. //{
  329. // if (deal == nullptr) return;
  330. //
  331. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  332. // if (!m_enable) return;
  333. // if (deal->Login() != m_trader) return;
  334. //
  335. // m_api->LoggerOut(MTLogOK, L"OnDealDelete, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  336. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  337. //}
  338. //void CPluginInstance::OnDealClean(const UINT64 login)
  339. //{
  340. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  341. // if (!m_enable) return;
  342. // if (login != m_trader) return;
  343. //
  344. // m_api->LoggerOut(MTLogOK, L"OndealClean, Login: %d", login);
  345. //}
  346. void CPluginInstance::OnDealPerform(const IMTDeal * deal, IMTAccount * account, IMTPosition * position)
  347. {
  348. // position为nullptr时,说明该deal不是由交易本身触发
  349. // account是deal完成后的用户状况
  350. // position是交易完成后的持仓状况
  351. // 对于deal是关闭一个持仓的情况,该position的volume会是0
  352. if (position == nullptr
  353. || deal == nullptr
  354. || account == nullptr)
  355. return;
  356. std::lock_guard<decltype(m_lock)> lk(m_lock);
  357. if (!m_enable) return;
  358. if (deal->Login() != m_trader) return;
  359. //m_api->LoggerOut(MTLogOK, L"OnDealPerform, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  360. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  361. // FIXME: 需要检查现在的deal是否和之前的order对应。如果没有记录到,则没法根本无法正常跟单以及平仓
  362. char order_buf[128];
  363. sprintf(order_buf, "%lld", deal->PositionID());
  364. IMTDeal* new_deal = m_api->DealCreate();
  365. std::vector<std::string>* fields = nullptr;
  366. ScopeGuard guard([new_deal, &fields]
  367. {
  368. new_deal->Release();
  369. if (fields)
  370. {
  371. fields->clear();
  372. delete fields;
  373. fields = nullptr;
  374. }
  375. });
  376. char login_buf[128];
  377. for (auto login : m_followers)
  378. {
  379. ScopeGuard g([position, &fields, this, login, login_buf]()
  380. {
  381. if (position->Volume() == 0)
  382. {
  383. if (fields == nullptr)
  384. fields = new(std::vector<std::string>);
  385. m_api->LoggerOut(MTLogOK, L"add field %lld to be delete", login);
  386. fields->push_back(login_buf);
  387. }
  388. });
  389. sprintf(login_buf, "%lld", login);
  390. auto fut = m_redis_client->hget(order_buf, login_buf);
  391. m_redis_client->sync_commit();
  392. auto reply = fut.get();
  393. m_api->LoggerOut(MTLogOK, L"%lld add deal, original deal #%lld", login, deal->Deal());
  394. // 如果不存在,忽略
  395. if (reply.ko()) continue;
  396. if (reply.is_null()) continue;
  397. // 获取context
  398. position_context context;
  399. memcpy(&context, reply.as_string().c_str(), sizeof(position_context));
  400. // 按建仓时的叙述,如果level或者position为0,亦忽略该记录
  401. if (context.level == 0) continue;
  402. if (context.position_id == 0) continue;
  403. uint64_t volume = context.level * deal->Volume() / 100;
  404. uint64_t volume_ext = context.level * deal->VolumeExt() / 100;
  405. uint64_t volume_closed = context.level * deal->VolumeClosed() / 100;
  406. uint64_t volume_closed_ext = context.level * deal->VolumeClosed() / 100;
  407. double prop = (double)volume / deal->Volume();
  408. double profit = deal->Profit() * prop;
  409. double commission = deal->Commission() * prop;
  410. double storage = deal->Storage() * prop;
  411. double raw_profit = deal->ProfitRaw() * prop;
  412. m_api->LoggerOut(MTLogOK, L"add new deal, volume %lld, volume closed %lld, order #%lld, position #%lld", volume, volume_closed, context.cur_ord, context.position_id);
  413. new_deal->Clear();
  414. new_deal->Assign(deal);
  415. new_deal->Login(login);
  416. new_deal->DealSet(0);
  417. new_deal->Volume(volume);
  418. new_deal->VolumeExt(volume_ext);
  419. new_deal->VolumeClosed(volume_closed);
  420. new_deal->VolumeClosedExt(volume_closed_ext);
  421. new_deal->ProfitRaw(raw_profit);
  422. new_deal->Profit(profit);
  423. new_deal->Commission(commission);
  424. new_deal->Storage(storage);
  425. new_deal->Order(context.cur_ord);
  426. new_deal->PositionID(context.position_id);
  427. MTAPIRES ret = m_api->DealAdd(new_deal);
  428. if (ret != MT_RET_OK)
  429. {
  430. // TODO: 有没有更多的错误处理?
  431. m_api->LoggerOut(MTLogErr, L"%lld cannot add deal [%d] to order #%lld, original deal: #%lld", login, ret, context.cur_ord, deal->Deal());
  432. continue;
  433. }
  434. m_api->LoggerOut(MTLogOK, L"add deal #%lld, original deal #%lld", new_deal->Deal(), deal->Deal());
  435. }
  436. m_api->LoggerOut(MTLogOK, L"deal #%lld, position #%lld, volume %lld", deal->Deal(), position->Position(), position->Volume());
  437. if (position->Volume() == 0)
  438. {
  439. // 如果平仓,则删除hash值
  440. if (position->Volume() == 0 && fields != nullptr)
  441. {
  442. m_redis_client->hdel(order_buf, *fields, [this](cpp_redis::reply& r)
  443. {
  444. if (r.ko())
  445. {
  446. // TODO 错误处理
  447. try
  448. {
  449. m_api->LoggerOut(MTLogErr, L"redis: %s", r.error().c_str());
  450. }
  451. catch (...)
  452. {
  453. }
  454. }
  455. });
  456. m_redis_client->commit();
  457. }
  458. // TODO 当position中的volume为0时,持仓被彻底平调,被跟订单是否也该检查
  459. }
  460. }
  461. MTAPIRES CPluginInstance::LoadParam()
  462. {
  463. MTAPIRES res = MT_RET_OK;
  464. IMTConParam* param = NULL;
  465. CMTStr128 tmp;
  466. if (!m_api || !m_config) return MT_RET_ERR_PARAMS;
  467. if ((res = m_api->PluginCurrent(m_config)) != MT_RET_OK)
  468. {
  469. m_api->LoggerOut(MTLogErr, L"failed to get current plugin configuration [%s (%u)]",
  470. SMTFormat::FormatError(res), res);
  471. return res;
  472. }
  473. if ((param = m_api->PluginParamCreate()) == NULL)
  474. {
  475. m_api->LoggerOut(MTLogErr, L"failed to create plugin parameter object");
  476. return MT_RET_ERR_MEM;
  477. }
  478. ScopeGuard param_release([param]()
  479. {
  480. param->Release();
  481. });
  482. std::lock_guard<decltype(m_lock)> lk(m_lock);
  483. //m_api->LoggerOut(MTLogOK, L"Load redis server params");
  484. if ((res = m_config->ParameterGet(L"Redis Server", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  485. {
  486. return(MT_RET_ERR_PARAMS);
  487. }
  488. std::string redis_server = ws2s(param->ValueString());
  489. if ((res = m_config->ParameterGet(L"Redis Port", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  490. {
  491. return(MT_RET_ERR_PARAMS);
  492. }
  493. int redis_port = param->ValueInt();
  494. //if ((res = m_config->ParameterGet(L"Redis User", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  495. //{
  496. // return(MT_RET_ERR_PARAMS);
  497. //}
  498. //std::string redis_user = ws2s(param->ValueString());
  499. if ((res = m_config->ParameterGet(L"Redis Password", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  500. {
  501. return(MT_RET_ERR_PARAMS);
  502. }
  503. std::string redis_password = ws2s(param->ValueString());
  504. if (m_redis_server != redis_server
  505. || m_redis_port != redis_port
  506. //|| m_redis_user != redis_user
  507. || m_redis_password != redis_password)
  508. {
  509. m_redis_server = redis_server;
  510. m_redis_port = redis_port;
  511. //m_redis_user = redis_user;
  512. m_redis_password = redis_password;
  513. stop_redis();
  514. if (start_redis())
  515. {
  516. if (!m_work_thread.joinable())
  517. {
  518. m_work_thread = std::thread(&CPluginInstance::keep_alive, this);
  519. }
  520. }
  521. else
  522. {
  523. m_api->LoggerOut(MTLogErr, L"failed to connect to redis server");
  524. return MT_RET_ERR_CONNECTION;
  525. }
  526. }
  527. //m_api->LoggerOut(MTLogOK, L"Load trade params");
  528. if ((res = m_config->ParameterGet(L"Trader", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  529. {
  530. return(MT_RET_ERR_PARAMS);
  531. }
  532. m_trader = param->ValueInt();
  533. if ((res = m_config->ParameterGet(L"Step", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  534. {
  535. return(MT_RET_ERR_PARAMS);
  536. }
  537. m_step = param->ValueInt();
  538. if ((res = m_config->ParameterGet(L"Tolerance", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  539. {
  540. return(MT_RET_ERR_PARAMS);
  541. }
  542. m_tolerance = param->ValueInt();
  543. if ((res = m_config->ParameterGet(L"Groups", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  544. {
  545. return(MT_RET_ERR_PARAMS);
  546. }
  547. wcsncpy(m_groups, param->ValueString(), 1024);
  548. //if ((res = m_config->ParameterGet(L"Logins", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  549. //{
  550. // return(MT_RET_ERR_PARAMS);
  551. //}
  552. //m_logins = param->ValueString();
  553. res = LoadLogins();
  554. if (res != MT_RET_OK)
  555. {
  556. m_api->LoggerOut(MTLogErr, L"failed to load clients [%d]", res);
  557. return res;
  558. }
  559. //m_api->LoggerOut(MTLogOK, L"Load param success");
  560. m_enable = true;
  561. return MT_RET_OK;
  562. }
  563. MTAPIRES CPluginInstance::LoadLogins()
  564. {
  565. m_followers.clear();
  566. IMTConGroup* group = m_api->GroupCreate();
  567. ScopeGuard group_guard([&]()
  568. {
  569. group->Release();
  570. });
  571. if (group == nullptr) return MT_RET_ERR_MEM;
  572. UINT total = m_api->GroupTotal();
  573. MTAPIRES ret = MT_RET_OK;
  574. std::vector<std::wstring> groups;
  575. for (int i = 0; i < total; i++)
  576. {
  577. ret = m_api->GroupNext(i, group);
  578. if (ret != MT_RET_OK) break;
  579. if (CheckGroup(m_groups, group->Group()) == FALSE) continue;
  580. m_api->LoggerOut(MTLogOK, L"group %s matched config", group->Group());
  581. groups.push_back(group->Group());
  582. }
  583. for (auto& group : groups)
  584. {
  585. UINT64* logins = nullptr;
  586. UINT total_users = 0;
  587. ret = m_api->UserLogins(group.c_str(), logins, total_users);
  588. m_api->LoggerOut(MTLogOK, L"add group %s, total users: %d", group.c_str(), total_users);
  589. if (ret == MT_RET_OK && logins != nullptr)
  590. {
  591. for (int i = 0; i < total_users; ++i)
  592. {
  593. m_api->LoggerOut(MTLogOK, L"add %d to list", logins[i]);
  594. m_followers.push_back(logins[i]);
  595. }
  596. }
  597. if (logins)
  598. {
  599. m_api->Free(logins);
  600. }
  601. }
  602. return ret;
  603. }
  604. bool CPluginInstance::start_redis()
  605. {
  606. try
  607. {
  608. m_redis_error_notified = false;
  609. if (m_redis_client)
  610. {
  611. if (m_redis_client->is_connected())
  612. return true;
  613. }
  614. m_redis_client.reset(new cpp_redis::client);
  615. m_redis_client->connect
  616. (
  617. m_redis_server,
  618. m_redis_port,
  619. [this](const std::string& host, std::size_t port, cpp_redis::connect_state status)
  620. {
  621. if (status == cpp_redis::connect_state::ok)
  622. {
  623. m_api->LoggerOut(MTLogOK, L"redis server connected");
  624. }
  625. },
  626. 500,
  627. 10000000,
  628. 1000
  629. );
  630. if (m_redis_password != "")
  631. {
  632. auto fut = m_redis_client->auth(m_redis_password);
  633. m_redis_client->sync_commit();
  634. auto reply = fut.get();
  635. if (reply.is_error())
  636. {
  637. m_api->LoggerOut(MTLogErr, L"connect: authentication failed");
  638. return false;
  639. }
  640. }
  641. }
  642. catch (tacopie::tacopie_error& e)
  643. {
  644. m_api->LoggerOut(MTLogErr, L"redis conn: %s", e.what());
  645. return false;
  646. }
  647. catch (std::exception& e)
  648. {
  649. m_api->LoggerOut(MTLogErr, L"redis conn: %s", e.what());
  650. return false;
  651. }
  652. catch (...)
  653. {
  654. m_api->LoggerOut(MTLogErr, L"failed to connect to server");
  655. return false;
  656. }
  657. return true;
  658. }
  659. void CPluginInstance::stop_redis()
  660. {
  661. try
  662. {
  663. if (m_redis_client)
  664. {
  665. m_redis_client->sync_commit();
  666. m_redis_client->disconnect();
  667. m_redis_client.reset();
  668. }
  669. }
  670. catch (tacopie::tacopie_error& e)
  671. {
  672. m_api->LoggerOut(MTLogErr, L"stop redis: %s", e.what());
  673. }
  674. catch (std::exception& e)
  675. {
  676. m_api->LoggerOut(MTLogErr, L"stop redis: %s", e.what());
  677. }
  678. catch (...)
  679. {
  680. m_api->LoggerOut(MTLogErr, L"stop redis: unknown error");
  681. }
  682. }
  683. void CPluginInstance::keep_alive()
  684. {
  685. using namespace std::chrono_literals;
  686. int counter = 500;
  687. while (m_enable)
  688. {
  689. if (counter-- <= 0)
  690. {
  691. counter = 500;
  692. std::lock_guard<decltype(m_lock)> lk(m_lock);
  693. if (m_redis_client)
  694. {
  695. if (m_redis_client->is_connected())
  696. {
  697. m_redis_client->ping([this](cpp_redis::reply& r)
  698. {
  699. if (r.ko())
  700. {
  701. m_redis_error_notified = true;
  702. if (!m_redis_error_notified)
  703. {
  704. m_api->LoggerOut(MTLogErr, L"redis: %s", r.error().c_str());
  705. }
  706. }
  707. });
  708. }
  709. else
  710. {
  711. m_redis_error_notified = true;
  712. if (!m_redis_error_notified)
  713. {
  714. m_api->LoggerOut(MTLogErr, L"redis server not connected");
  715. }
  716. stop_redis();
  717. start_redis();
  718. }
  719. }
  720. }
  721. std::this_thread::sleep_for(16ms);
  722. }
  723. }